API Reference
This page provides all docstrings locally defined in the QuantumControl package for both private and public symbols. See also the summary of the public API.
QuantumControl exposes local exported and unexported local symbols as well as re-exporting symbols and sub-modules from the QuantumPropagators subpackage and some of its submodules.
The QuantumControl submodules provide additional public functionality. Note that some of the most commonly used symbols from QuantumControl's submodules may also be re-exported at the top-level (such as @optimize_or_load from the QuantumControl.Workflows submodule).
Local Exported Symbols
QuantumControl.ControlProblem — Type
A full control problem with multiple trajectories.
ControlProblem(
trajectories,
tlist;
kwargs...
)The trajectories are a list of Trajectory instances, each defining an initial state and a dynamical generator for the evolution of that state. Usually, the trajectory will also include a target state (see Trajectory) and possibly a weight. The trajectories may also be given together with tlist as a mandatory keyword argument.
The tlist is the time grid on which the time evolution of the initial states of each trajectory should be propagated. It may also be given as a (mandatory) keyword argument.
The remaining kwargs are keyword arguments that are passed directly to the optimal control method. These typically include e.g. the optimization functional.
The control problem is solved by finding a set of controls that minimize an optimization functional over all trajectories.
QuantumControl.Trajectory — Type
Description of a state's time evolution.
Trajectory(
initial_state,
generator;
target_state=nothing,
weight=1.0,
kwargs...
)describes the time evolution of the initial_state under a time-dependent dynamical generator (e.g., a Hamiltonian or Liouvillian).
Trajectories are central to quantum control problems: an optimization functional depends on the result of propagating one or more trajectories. For example, when optimizing for a quantum gate, the optimization considers the trajectories of all logical basis states.
In addition to the initial_state and generator, a Trajectory may include data relevant to the propagation and to evaluating a particular optimization functional. Most functionals have the notion of a "target state" that the initial_state should evolve towards, which can be given as the target_state keyword argument. In some functionals, different trajectories enter with different weights [21], which can be given as a weight keyword argument. Any other keyword arguments are also available to a functional as properties of the Trajectory .
A Trajectory can also be instantiated using all keyword arguments.
Properties
All keyword arguments used in the instantiation are available as properties of the Trajectory. At a minimum, this includes initial_state, generator, target_state, and weight.
By convention, properties with a prop_ prefix, e.g., prop_method, will be taken into account when propagating the trajectory. See propagate_trajectory for details.
QuantumControl.optimize — Function
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.
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. 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 (aKrotovResult, or a result that can be converted to aKrotovResult). The optimization starts from the optimized controls of that result, and the iteration numbers continue from its last iteration (iter_startis ignored). AKrotovResultgiven ascontinue_fromis updated in place and returned.use_threads=false: Iftrue, propagate the different trajectories in parallel, using multiple threads.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. 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 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 after the guess has been evaluated 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. An exception that occurs before the guess has been evaluated, or in thecallbackfor the guess, is always thrown.
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 and any problem 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.
If the same parameter is set in more than one way, the following rules determine which setting is used:
- Any problem keyword argument (including keyword arguments passed directly to
optimize) that applies to a propagation overrides any property of aTrajectoryfor that propagation, regardless of the prefix. - Among the problem keyword arguments, and among the properties of a
Trajectory, afw_prop_orbw_prop_prefix overrides theprop_prefix.
For example, a prop_method problem 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 problem keyword argument. Since this overrides any per-trajectory setting, use trajectory properties instead if different trajectories require different propagation methods. Krotov's method requires a piecewise propagation method (see init_prop); other methods are rejected.
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.
QuantumControl.propagate_trajectories — Function
Propagate multiple trajectories in parallel.
result = propagate_trajectories(
trajectories, tlist; use_threads=true, kwargs...
)runs propagate_trajectory for every trajectory in trajectories, collects and returns a vector of results. The propagation happens in parallel if use_threads=true (default). All keyword parameters are passed to propagate_trajectory, except that if initial_state is given, it must be a vector of initial states, one for each trajectory. Likewise, to pass pre-allocated storage arrays to storage, a vector of storage arrays must be passed. A simple storage=true will still work to return a vector of storage results.
QuantumControl.propagate_trajectory — Function
Propagate a Trajectory.
propagate_trajectory(
traj,
tlist;
initial_state=traj.initial_state,
kwargs...
)propagates initial_state under the dynamics described by traj.generator. It takes the same keyword arguments as QuantumPropagators.propagate, with default values from any property of traj with a prop_ prefix (prop_method, prop_inplace, prop_callback, …). See init_prop_trajectory for details.
Note that method (a mandatory keyword argument in QuantumPropagators.propagate) must be specified, either as a property prop_method of the trajectory, or by passing a method keyword argument explicitly.
Local Unexported Symbols
QuantumControl.AbstractOptimizationResult — Type
Abstract type for the result object returned by optimize. Any optimization method implemented on top of QuantumControl should subtype from AbstractOptimizationResult. This enables conversion between the results of different methods, allowing one method to continue an optimization from another method.
In order for this to work seamlessly, result objects should use a common set of field names as much as a possible. When a result object requires fields that cannot be provided by all other result objects, it should have default values for these field, which can be defined in a custom Base.convert method, as, e.g.,
function Base.convert(::Type{MyResult}, result::AbstractOptimizationResult)
defaults = Dict{Symbol,Any}(
:f_calls => 0,
:fg_calls => 0,
)
return convert(MyResult, result, defaults)
endWhere f_calls and fg_calls are fields of MyResult that are not present in a given result of a different type. The three-argument convert is defined internally for any AbstractOptimizationResult.
QuantumControl.chain_callbacks — Function
Combine multiple callback functions.
chain_callbacks(funcs...)combines funcs into a single Function that can be passes as callback to ControlProblem or any optimize-function.
Each function in func must be a suitable callback by itself. This means that it should receive the optimization workspace object as its first positional parameter, then positional parameters specific to the optimization method, and then an arbitrary number of data parameters. It must return either nothing or a tuple of "info" objects (which will end up in the records field of the optimization result).
When chaining callbacks, the funcs will be called in series, and the "info" objects will be accumulated into a single result tuple. The combined results from previous funcs will be given to the subsequent funcs as data parameters. This allows for the callbacks in the chain to communicate.
The chain will return the final combined result tuple, or nothing if all funcs return nothing.
When calling optimize, any callback that is a tuple will be automatically processed with chain_callbacks. Thus, chain_callbacks rarely has to be invoked manually.
QuantumControl.init_prop_trajectory — Function
Initialize a propagator for a given Trajectory.
propagator = init_prop_trajectory(
traj,
tlist;
initial_state=traj.initial_state,
kwargs...
)initializes a Propagator for the propagation of the initial_state under the dynamics described by traj.generator.
All keyword arguments are forwarded to QuantumPropagators.init_prop, with default values from any property of traj with a prop_ prefix. That is, the keyword arguments for the underlying QuantumPropagators.init_prop are determined as follows:
- For any property of
trajwhose name starts with the prefixprop_, strip the prefix and use that property as a keyword argument forinit_prop. For example, iftraj.prop_methodis defined,method=traj.prop_methodwill be passed toinit_prop. Similarly,traj.prop_inplacewould be passed asinplace=traj.prop_inplace, etc. - Any explicit keyword argument to
init_prop_trajectoryoverrides the values from the properties oftraj.
Note that the propagation method in particular must be specified, as it is a mandatory keyword argument in QuantumPropagators.propagate). Thus, either traj must have a property prop_method of the trajectory, or method must be given as an explicit keyword argument.
QuantumControl.make_print_iters — Function
Construct a method-specific automatic callback for printing iter information.
print_iters = make_print_iters(Method; kwargs...)constructs the automatic callback to be used by optimize(problem; method=Method, print_iters=true) to print information after each iteration. The keyword arguments are those used to instantiate problem and those explicitly passed to optimize.
Optimization methods should implement make_print_iters(::Val{:Method}; kwargs...) where :Method is the name of the module/package implementing the method.
QuantumControl.remove_atexit_save_optimization — Function
Remove a callback registered by set_atexit_save_optimization.
remove_atexit_save_optimization(hook)removes hook, as returned by set_atexit_save_optimization, from Base.atexit_hooks, regardless of its position, so any atexit hooks registered after it are unaffected. Only a single entry equal (===) to hook is removed. If hook is not registered (e.g., because it was already removed), or if hook is nothing, this does nothing.
QuantumControl.set_atexit_save_optimization — Function
Register a callback to dump a running optimization to disk on unexpected exit.
hook = set_atexit_save_optimization(
filename, result; msg_property=:message, msg="Abort: ATEXIT"
)registers a callback via atexit that writes the given result object to the given filename in JLD2 format in the event that the program terminates unexpectedly, and returns that callback. The idea is to avoid data loss if the user presses CTRL-C in a non-interactive program (SIGINT), or if the process receives a SIGTERM from an HPC scheduler because the process has reached its allocated runtime limit. Note that the callback cannot protect against data loss in all possible scenarios, e.g., a SIGKILL will terminate the program without giving the callback a chance to run (as will yanking the power cord).
A long-running optimization routine should use
hook = nothing
if !isnothing(atexit_filename)
hook = set_atexit_save_optimization(atexit_filename, result)
end
try
# ... optimization ...
finally
remove_atexit_save_optimization(hook)
endThat is, the optimization routine should make set_atexit_save_optimization conditional on an atexit_filename keyword argument, which is what @optimize_or_load will pass to the optimization routine. The optimization routine must remove the callback with remove_atexit_save_optimization when it exits, both normally and by throwing an exception. Otherwise, in an interactive session, the callback remains registered and overwrites filename with the (partial) result when Julia eventually exits. To ensure this, register the callback immediately before the try block, with no code in between that might throw. Since an exception removes the callback, the callback does not write filename if the optimization fails with an exception, even if that exception ends the program. A SIGINT or SIGTERM in a non-interactive program terminates Julia without running the finally block, so the callback still runs in that case. Note that in an interactive context, CTRL-C will throw an InterruptException, but not cause a shutdown. Optimization routines that want to prevent data loss in this situation should handle the InterruptException and return result, in addition to using set_atexit_save_optimization.
If msg_property is not nothing, the given msg string will be stored in the corresponding property of the (mutable) result object before it is written out.
The resulting JLD2 file is compatible with QuantumControl.load_optimization.
QuantumControl.set_default_ad_framework — Function
Set the default provider for automatic differentiation.
QuantumControl.set_default_ad_framework(mod; quiet=false)registers the given module (package) as the default AD framework.
This determines the default setting for the automatic parameter in the following functions:
QuantumControl.Functionals.make_chiQuantumControl.Functionals.make_gate_chiQuantumControl.Functionals.make_grad_J_a
The given mod must be a supported AD framework, e.g.,
import Zygote
QuantumControl.set_default_ad_framework(Zygote)Currently, there is built-in support for Zygote and FiniteDifferences.
For other packages to be used as the default AD framework, the appropriate methods for make_chi etc. must be defined.
Unless quiet=true, calling set_default_ad_framework will show a message to confirm the setting.
To unset the default AD framework, use
QuantumControl.set_default_ad_framework(nothing)$\gdef\tgt{\text{tgt}}$ $\gdef\tr{\operatorname{tr}}$ $\gdef\Re{\operatorname{Re}}$ $\gdef\Im{\operatorname{Im}}$
List of Submodules
QuantumControl has the following sub-modules:
QuantumControl.AmplitudesQuantumControl.ControlsQuantumControl.FunctionalsQuantumControl.GeneratorsQuantumControl.InterfacesQuantumControl.PulseParameterizationsQuantumControl.ShapesQuantumControl.StorageQuantumControl.Workflows
QuantumControl.Amplitudes
Re-exported Symbols:
QuantumControl.Controls
Public Symbols:
Re-exported Symbols:
ParameterizedFunctionStaticParameterdiscretizediscretize_on_midpointsevaluateevaluate!get_controlsget_parametersget_tlist_midpointssubstitutet_mid
Public Symbols from Other Modules (not exported):
Public Symbols
QuantumControl.Controls.get_control_deriv — Function
Get the derivative of the generator $G$ w.r.t. the control $ϵ(t)$.
μ = get_control_deriv(generator, control)returns nothing if the generator (Hamiltonian or Liouvillian) does not depend on control, or a generator
\[μ = \frac{∂G}{∂ϵ(t)}\]
otherwise. For linear control terms, μ will be a static operator, e.g. an AbstractMatrix or an Operator. For non-linear controls, μ will be time-dependent, e.g. a Generator. In either case, evaluate should be used to evaluate μ into a constant operator for particular values of the controls and a particular point in time.
For constant generators, e.g. an Operator, the result is always nothing.
a = get_control_deriv(ampl, control)returns the derivative $∂a_l(t)/∂ϵ_{l'}(t)$ of the given amplitude $a_l(\{ϵ_{l''}(t)\}, t)$ with respect to the given control $ϵ_{l'}(t)$. For "trivial" amplitudes, where $a_l(t) ≡ ϵ_l(t)$, the result with be either 1.0 or 0.0 (depending on whether ampl ≡ control). For non-trivial amplitudes, the result may be another amplitude that depends on the controls and potentially on time, but can be evaluated to a constant with evaluate.
QuantumControl.Controls.get_control_derivs — Function
Get a vector of the derivatives of generator w.r.t. each control.
get_control_derivs(generator, controls)returns a vector containing the derivative of generator with respect to each control in controls, as obtained from get_control_deriv.
QuantumControl.Controls.get_parameter_deriv — Function
Get the derivative of an object with respect to a single control parameter.
D = get_parameter_deriv(object, block, i)returns the derivative of a control, an amplitude, or a generator with respect to the control parameter $u =$ block[i]. A parameter is identified by the pair (block, i) of a parameter block (compared with ===) and a linear index into that block. The block must be a single block as held by a control or by a custom generator type, e.g., an element of get_parameters(object).x, not the parameters of an object as returned by get_parameters; passing the latter throws an ArgumentError. Use get_parameter_derivs for the derivatives with respect to all parameters of an object.
The derivative is an object of the same kind as object:
object | Return value |
|---|---|
| control | 0.0 if the control does not depend on block[i], otherwise a number, a function of t without parameters, or a control that holds block |
| amplitude | 0.0, a number, or an amplitude |
| generator | nothing if the generator does not depend on block[i], otherwise a static operator or a Generator |
These are the conventions of get_control_deriv. A derivative D is evaluated with evaluate with the same arguments as object, e.g., evaluate(D, tlist, n; vals_dict). It reads the current parameter values when it is evaluated, so it remains valid while an optimizer mutates the parameters. A derivative never holds a new parameter block: the derivative of a control holds the block of the original control, or none at all. Thus, get_parameter_deriv can be applied to a derivative again, to obtain higher derivatives, if the objects involved support it.
Implementing parameter derivatives
The author of a ParameterizedFunction defines the two-argument method
get_parameter_deriv(control::MyParameterizedFunction, i)which returns the derivative with respect to control.parameters[i]: a number for a constant derivative (including 0.0), a function of t without parameters, or a ParameterizedFunction that holds the same block, control.parameters, and reads the values from it when it is called. There is no fallback: a ParameterizedFunction without this method raises a MethodError. The two-argument method is for authors only. Consumers always call the three-argument method, which returns 0.0 unless block === control.parameters.
Everything else is generic: functions that are not a ParameterizedFunction, vectors of pulse values, and LockedAmplitude instances have the derivative 0.0. Any other amplitude $a(t)$ uses the chain rule
\[\frac{∂a(t)}{∂u} = \sum_l \frac{∂a(t)}{∂ϵ_l(t)} \frac{∂ϵ_l(t)}{∂u}\]
over its controls $ϵ_l(t)$ (as returned by get_controls), with get_control_deriv for the first factor. Thus, any amplitude that supports get_control_deriv also supports get_parameter_deriv. For a Generator with operators $Ĥ_i$ and amplitudes $a_i(t)$, the derivative is
\[\frac{∂Ĥ(t)}{∂u} = \sum_i Ĥ_i \frac{∂a_i(t)}{∂u}\,,\]
where a term is dropped if the derivative of its amplitude is 0.0, and the operator $Ĥ_i$ is scaled if that derivative is a number. Static operators have the derivative nothing.
A custom generator type that holds parameter blocks in its own fields (i.e., that has a custom get_parameters method), or that contains parameterized controls, must implement the three-argument method itself. That method recognizes the blocks that it holds by identity (===), and applies the chain rule for the blocks of its controls. Without it, the generic method raises an error, instead of returning a derivative that is silently zero.
The get_parameter_deriv function is meant for setting up a propagation or an optimization. Call it once and keep the result, instead of calling it repeatedly. See Controls and Derivatives for details.
See also
get_parameter_derivs— derivatives with respect to all parametersQuantumControl.Interfaces.check_controlandQuantumControl.Interfaces.check_generator— verify the derivatives
QuantumControl.Controls.get_parameter_derivs — Function
Get a vector of the derivatives of object w.r.t. each control parameter.
derivs = get_parameter_derivs(object, parameters)returns a vector of the same length as parameters, where element n is the derivative of object (a control, an amplitude, or a generator) with respect to parameters[n], as obtained from get_parameter_deriv.
The parameters may be the parameters of any object, as returned by get_parameters, e.g., of the object itself, or of a ControlProblem that contains object, or a single parameter block. The function calls get_parameter_deriv(object, block, i) for each element (block, i) of the blocks of parameters, which are parameters.x for the result of get_parameters. The derivatives with respect to the parameters in a block that object does not hold or inherit are 0.0 for controls and amplitudes and nothing for generators. This includes all parameters of a copy of the parameters, since blocks are identified by ===.
For example, for a ControlProblem,
u = get_parameters(problem)
for traj in problem.trajectories
derivs = get_parameter_derivs(traj.generator, u)
# length(derivs) == length(u)
endThe get_parameter_derivs function is meant for setting up a propagation or an optimization. Call it once and keep the result, instead of calling it repeatedly.
QuantumControl.Functionals
Public Symbols:
J_T_reJ_T_smJ_T_ssJ_a_avg_zeroJ_a_fluenceJ_bgate_functionalmake_chimake_gate_chimake_grad_J_amake_xi
Private Symbols:
Public Symbols
QuantumControl.Functionals.J_T_re — Function
Real-part functional.
J_T_re(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates
\[J_{T,\text{re}} = 1 - F_{\text{re}} \quad\in \begin{cases} [0, 2] & \text{in Hilbert space} \\ [0, 1] & \text{in Liouville space.} \end{cases}\]
All arguments are passed to f_tau while evaluating $F_{\text{re}}$ in F_re.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.J_T_sm — Function
Square-modulus functional.
J_T_sm(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates
\[J_{T,\text{sm}} = 1 - F_{\text{sm}} \quad\in [0, 1].\]
All arguments are passed to f_tau while evaluating $F_{\text{sm}}$ in F_sm.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.J_T_ss — Function
State-to-state phase-insensitive functional.
J_T_ss(Ψ, trajectories; tau=taus(Ψ, trajectories); τ=tau)calculates
\[J_{T,\text{ss}} = 1 - F_{\text{ss}} \in [0, 1].\]
All arguments are passed to F_ss.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.J_a_avg_zero — Function
Running cost penalizing a non-zero pulse area.
J_a = J_a_avg_zero(pulsevals, tlist)calculates
\[J_a = \sum_l \left(\int_0^T ϵ_l(t)\, dt\right)^2 \approx \sum_l A_l^2\,, \quad A_l = \sum_n ϵ_{nl}\, dt_n\,,\]
where $ϵ_{nl}$ and $dt_n$ are as in J_a_fluence. The functional is zero when every control integrates to zero over the time grid, and positive otherwise.
In conjunction with QuantumPropagators.Amplitudes.GuidedAmplitude, this enables an optimization that preserves the pulse area of a given guide.
See also
grad_J_a_avg_zero— analytic (automatic) gradient
QuantumControl.Functionals.J_a_fluence — Function
Running cost for the pulse fluence.
J_a = J_a_fluence(pulsevals, tlist)calculates
\[J_a = \sum_l \int_0^T |ϵ_l(t)|^2 dt \approx \sum_{nl} |ϵ_{nl}|^2 \, dt_n\]
where $ϵ_{nl}$ are the values in pulsevals, with n the index of the time interval and l the index of the control, and $dt_n =$ tlist[n+1] - tlist[n] is the duration of interval n. The pulsevals are vectorized as $[ϵ₁₁, ϵ₂₁, …, ϵ_{N_T,1}, ϵ₁₂, ϵ₂₂, …]$, where N_T = length(tlist) - 1. Supports non-uniform time grids.
See also
grad_J_a_fluence— analytic (automatic) gradient
QuantumControl.Functionals.J_b — Function
Evaluate a state-dependent running cost functional.
J_b_val = J_b(storage, trajectories, tlist; g_b)returns
\[J_b = ∑_k ∑_{n=0}^{N_T}{}^′ g_b(|Ψ_k(t_n)⟩) Δt_n\]
as the trapezoid discretization of the integral
\[J_b = ∑_k ∫_0^T g_b(|Ψ_k(t)⟩) dt ,\]
where storage[k] contains the forward-propagated states for trajectory k at each time grid point in tlist, $t_0 = 0, t_1, … t_{N_T} = T$; for example, the fw_storage component of the GRAPE workspace. The $Δt_n$ are defined at the endpoints as $Δt_0 = t_1 - t_0$ and $Δt_{N_T} = (t_{N_T} - t_{N_T-1})$, and at the interior points as $Δt_n = \frac{(t_{n+1} - t_{n-1})}{2}$. For uniform time grids, $Δt_n ≡ dt$. The prime in the sum over $n$ indicates that the terms at the endpoints $n=0$ and $n=N_T$ are halved.
Note that g_b is a mandatory keyword argument and must be a function g_b(Ψ, trajectory, tlist, n) -> Float64 where Ψ is the state $|Ψ(t)⟩$ at $t$ corresponding to the (one-based) time grid point tlist[n], and trajectory is a QuantumControl.Trajectory that may hold additional data in a custom property that is relevant to the calculation of $g_b$.
The definition of J_b here is compatible with the treatment of running costs in GRAPE.
QuantumControl.Functionals.gate_functional — Function
Convert a functional from acting on a gate to acting on propagated states.
J_T = gate_functional(J_T_U; kwargs...)constructs a functional J_T that meets the requirements for for Krotov/GRAPE and make_chi. That is, the output J_T takes positional positional arguments Ψ and trajectories. The input functional J_T_U is assumed to have the signature J_T_U(U; kwargs...) where U is a matrix with elements $U_{ij} = ⟨Ψ_i|Ψ_j⟩$, where $|Ψ_i⟩$ is the initial_state of the i'th trajectories (assumed to be the i'th canonical basis state) and $|Ψ_j⟩$ is the result of forward-propagating $|Ψ_j⟩$. That is, U is the projection of the time evolution operator into the subspace defined by the basis in the initial_states of the trajectories.
See also
make_gate_chi— create a correspondingchifunction that acts more efficiently than the generalmake_chi.
QuantumControl.Functionals.make_chi — Function
Return a function that calculates $|χ_k⟩ = -∂J_T/∂⟨Ψ_k|$.
chi = make_chi(
J_T,
trajectories;
mode=:any,
automatic=:default,
via=:automatic, # one of :automatic, :tau, :states
)creates a function chi(Ψ, trajectories) or chi(Ψ, trajectories; tau) that returns a vector of states χ with $|χ_k⟩ = -∂J_T/∂⟨Ψ_k|$, where $|Ψ_k⟩$ is the k'th element of Ψ. These are the states used as the boundary condition for the backward propagation propagation in Krotov's method and GRAPE.
The resulting chi function takes the keyword argument tau if and only if via=:tau or via=:automatic (default) if the following conditions are met:
- All
trajectorieshave a definedtarget_statecomponent (notnothing) J_Ttakestauas a keyword argument (determined via introspection)
Both of these conditions are requirements for via=:tau.
Each $|χₖ⟩$ is defined as a matrix calculus Wirtinger derivative,
\[|χ_k(T)⟩ = -\frac{∂J_T}{∂⟨Ψ_k|} = -\frac{1}{2} ∇_{Ψ_k} J_T\,;\qquad ∇_{Ψ_k} J_T ≡ \frac{∂J_T}{\Re[Ψ_k]} + i \frac{∂J_T}{\Im[Ψ_k]}\,.\]
The function J_T must take a vector of states Ψ and a vector of trajectories as positional parameters. If via=:tau, it must also a vector tau as a keyword argument, see e.g. J_T_sm). that contains the overlap of the states Ψ with the target states from the trajectories
The derivative can be calculated analytically of automatically (via automatic differentiation) depending on the value of mode. For mode=:any, an analytic derivative is returned if available, with a fallback to an automatic derivative.
If mode=:analytic, return an analytically known $-∂J_T/∂⟨Ψ_k|$, e.g.,
QuantumControl.Functionals.J_T_sm→QuantumControl.Functionals.chi_sm,QuantumControl.Functionals.J_T_re→QuantumControl.Functionals.chi_re,QuantumControl.Functionals.J_T_ss→QuantumControl.Functionals.chi_ss.
and throw an error if no analytic derivative is known.
If mode=:automatic, return an automatic derivative (even if an analytic derivative is known). The calculation of an automatic derivative (whether via mode=:any or mode=:automatic) requires that a suitable framework (e.g., Zygote or FiniteDifferences) has been loaded. The loaded module must be passed as automatic keyword argument. Alternatively, it can be registered as a default value for automatic by calling QuantumControl.set_default_ad_framework.
When evaluating $|χ_k⟩$ automatically, if via=:states is given , $|χ_k(T)⟩$ is calculated directly as defined above from the gradient with respect to the states $\{|Ψ_k(T)⟩\}$.
If via=:tau is given instead, the functional $J_T$ is considered a function of overlaps $τ_k = ⟨Ψ_k^\tgt|Ψ_k(T)⟩$. This requires that all trajectories define a target_state and that J_T calculates the value of the functional solely based on the values of tau passed as a keyword argument. With only the complex conjugate $τ̄_k = ⟨Ψ_k(T)|Ψ_k^\tgt⟩$ having an explicit dependency on $⟨Ψ_k(T)|$, the chain rule in this case is
\[|χ_k(T)⟩ = -\frac{∂J_T}{∂⟨Ψ_k|} = -\left( \frac{∂J_T}{∂τ̄_k} \frac{∂τ̄_k}{∂⟨Ψ_k|} \right) = - \frac{1}{2} (∇_{τ_k} J_T) |Ψ_k^\tgt⟩\,.\]
Again, we have used the definition of the Wirtinger derivatives,
\[\begin{align*} \frac{∂J_T}{∂τ_k} &≡ \frac{1}{2}\left( \frac{∂ J_T}{∂ \Re[τ_k]} - i \frac{∂ J_T}{∂ \Im[τ_k]} \right)\,,\\ \frac{∂J_T}{∂τ̄_k} &≡ \frac{1}{2}\left( \frac{∂ J_T}{∂ \Re[τ_k]} + i \frac{∂ J_T}{∂ \Im[τ_k]} \right)\,, \end{align*}\]
and the definition of the Zygote gradient with respect to a complex scalar,
\[∇_{τ_k} J_T = \left( \frac{∂ J_T}{∂ \Re[τ_k]} + i \frac{∂ J_T}{∂ \Im[τ_k]} \right)\,.\]
In order to extend make_chi with an analytic implementation for a new J_T function, define a new method make_analytic_chi like so:
QuantumControl.Functionals.make_analytic_chi(::typeof(J_T_sm), trajectories) = chi_smwhich links make_chi for QuantumControl.Functionals.J_T_sm to QuantumControl.Functionals.chi_sm.
QuantumControl.Functionals.make_gate_chi — Function
Return a function to evaluate $|χ_k⟩ = -∂J_T(Û)/∂⟨Ψ_k|$ via the chain rule.
chi = make_gate_chi(J_T_U, trajectories; automatic=:default, kwargs...)returns a function equivalent to
chi = make_chi(
gate_functional(J_T_U; kwargs...),
trajectories;
mode=:automatic,
automatic,
)\[\begin{split} |χ_k⟩ &= -\frac{∂}{∂⟨Ψ_k|} J_T \\ &= - \frac{1}{2} \sum_i (∇_U J_T)_{ik} \frac{∂ U_{ik}}{∂⟨Ψ_k|} \\ &= - \frac{1}{2} \sum_i (∇_U J_T)_{ik} |Ψ_i⟩ \end{split}\]
where $|Ψ_i⟩$ is the basis state stored as the initial_state of the i'th trajectory, see gate_functional.
The gradient $∇_U J_T$ is obtained via automatic differentiation (AD). This requires that an AD package has been loaded (e.g., using Zygote). This package must either be passed as the automatic keyword argument, or the package must be set as the default AD provider using QuantumControl.set_default_ad_framework.
Compared to the more general make_chi with mode=:automatic, make_gate_chi will generally have a slightly smaller numerical overhead, as it pushes the use of automatic differentiation down by one level.
QuantumControl.Functionals.make_grad_J_a — Function
Return a function to evaluate $∂J_a/∂ϵ_{ln}$ for a pulse value running cost.
grad_J_a = make_grad_J_a(
J_a,
tlist;
mode=:any,
automatic=:default,
)returns a function so that ∇J_a = grad_J_a(pulsevals, tlist) returns a vector ∇J_a containing the vectorized elements $∂J_a/∂ϵ_{ln}$. The function J_a must have the interface J_a(pulsevals, tlist), see, e.g., J_a_fluence.
In pulsevals, the values $ϵ_{nl}$ are vectorized with n (time interval index) varying faster than l (control index), i.e., pulsevals = [ϵ₁₁, ϵ₂₁, …, ϵ_{N_T,1}, ϵ₁₂, ϵ₂₂, …, ϵ_{N_T,2}, …], where $N_T =$ length(tlist) - 1. The pulse values for each control are contiguous.
The parameters mode and automatic are handled as in make_chi, where mode is one of :any, :analytic, :automatic, and automatic is he loaded module of an automatic differentiation framework, where :default refers to the framework set with QuantumControl.set_default_ad_framework.
In order to extend make_grad_J_a with an analytic implementation for a new J_a function, define a new method make_analytic_grad_J_a like so:
make_analytic_grad_J_a(::typeof(J_a_fluence), tlist) = grad_J_a_fluencewhich links make_grad_J_a for J_a_fluence to grad_J_a_fluence.
QuantumControl.Functionals.make_xi — Function
Return a function that calculates $|ξ_k(t_n)⟩ = -∂g_b/∂⟨Ψ_k(t_n)|$.
xi = make_xi(g_b; mode=:any, automatic=:default)returns a function xi(Ψ, trajectory, tlist, n) that evaluates
\[|ξ_k(t_n)⟩ = -\frac{∂ (g_b)_{kn}}{∂ ⟨Ψ_k(t_n)|}\]
where g_b(Ψ, trajectory, tlist, n) -> Float64 is a per-trajectory, per-time-point running cost, cf. J_b. Note the minus sign, which is included in the definition to match the minus sign in make_chi. Both in g_b and xi, the argument n is a one-based index into the time grid tlist. Since a QuantumControl.Trajectory can contain arbitrary (custom) properties, a g_b function may reference such custom properties where appropriate, and xi will have access to the same trajectory as g_b itself.
The mode and automatic parameters work as in QuantumControl.Functionals.make_chi. With mode=:any (default), an analytic xi is used if available (via make_analytic_xi, see below), falling back to automatic differentiation otherwise. With mode=:analytic, only the analytic path is attempted. With mode=:automatic, only automatic differentiation is used.
The automatic parameter specifies the AD backend module (or :default to use the framework set via QuantumControl.set_default_ad_framework). For example, with automatic=Zygote (loaded via import Zygote), g_b is differentiated with respect to Ψ using Wirtinger calculus:
xi(Ψ, ...) = -0.5 * Zygote.gradient(psi -> g_b(psi, ...), Ψ)[1]Private Symbols
QuantumControl.Functionals.grad_J_a_avg_zero — Function
Analytic derivative for J_a_avg_zero.
∇J_a = grad_J_a_avg_zero(pulsevals, tlist)returns ∇J_a with elements $2 A_l\, dt_n$, where $A_l = \sum_n ϵ_{nl}\, dt_n$ is the time integral of control l.
QuantumControl.Functionals.taus! — Function
Overlaps of target states with propagates states, calculated in-place.
taus!(τ, Ψ, trajectories; ignore_missing_target_state=false)overwrites the complex vector τ with the results of taus(Ψ, trajectories).
Throws an ArgumentError if any of trajectories have a target_state of nothing. If ignore_missing_target_state=true, values in τ instead will remain unchanged for any trajectories with a missing target state.
QuantumControl.Functionals.chi_re — Function
Backward boundary states $|χ⟩$ for functional J_T_re.
χ chi_re(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates the vector of states χ according to
\[|χ_k⟩ = -\frac{∂ J_{T,\text{re}}}{∂ ⟨Ψ_k(T)|} = \frac{1}{2N} w_k |Ψ^{\tgt}_k⟩\]
with $|Ψ^{\tgt}_k⟩$ and $w_k$ as defined in f_tau.
Note: this function can be obtained with make_chi(J_T_re, trajectories).
QuantumControl.Functionals.F_ss — Function
State-to-state phase-insensitive fidelity.
F_ss(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates
\[F_{\text{ss}} = \frac{1}{N} \sum_{k=1}^{N} w_k |τ_k|^2 \quad\in [0, 1]\]
with $N$, $w_k$ and $τ_k$ as in f_tau.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.chi_ss — Function
Backward boundary states $|χ⟩$ for functional J_T_ss.
χ = chi_ss(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates the vector of states χ according to
\[|χ_k⟩ = -\frac{∂ J_{T,\text{ss}}}{∂ ⟨Ψ_k(T)|} = \frac{1}{N} w_k τ_k |Ψ^{\tgt}_k⟩\,,\]
with $|Ψ^{\tgt}_k⟩$, $τ_k$ and $w_k$ as defined in f_tau.
Note: this function can be obtained with make_chi(J_T_ss, trajectories).
QuantumControl.Functionals.F_sm — Function
Square-modulus fidelity.
F_sm(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates
\[F_{\text{sm}} = |f_τ|^2 = \left\vert\frac{1}{N} \sum_{k=1}^{N} w_k τ_k\right\vert^2 = \frac{1}{N^2} \sum_{k=1}^{N} \sum_{j=1}^{N} w_k w_j τ̄_k τ_j \quad\in [0, 1]\,,\]
with $w_k$ the weight for the k'th trajectory and $τ_k$ the overlap of the k'th propagated state with the k'th target state, $τ̄_k$ the complex conjugate of $τ_k$, and $N$ the number of trajectories.
All arguments are passed to f_tau to evaluate $f_τ$.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.taus — Function
Overlaps of target states with propagates states
τ = taus(Ψ, trajectories)calculates a vector of values $τ_k = ⟨Ψ_k^{tgt}|Ψ_k⟩$ where $|Ψ_k^{tgt}⟩$ is the traj.target_state of the $k$'th element of trajectories and $|Ψₖ⟩$ is the $k$'th element of Ψ.
The definition of the τ values with $Ψ_k^{tgt}$ on the left (overlap of target states with propagated states, as opposed to overlap of propagated states with target states) matches Refs. [12] and [22].
The function requires that each trajectory defines a target state. See also taus! for an in-place version that includes well-defined error handling for any trajectories whose target_state property is nothing.
QuantumControl.Functionals.F_re — Function
Real-part fidelity.
F_re(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates
\[F_{\text{re}} = \Re[f_{τ}] = \Re\left[ \frac{1}{N} \sum_{k=1}^{N} w_k τ_k \right] \quad\in \begin{cases} [-1, 1] & \text{in Hilbert space} \\ [0, 1] & \text{in Liouville space.} \end{cases}\]
with $w_k$ the weight for the k'th trajectory and $τ_k$ the overlap of the k'th propagated state with the k'th target state, and $N$ the number of trajectories.
All arguments are passed to f_tau to evaluate $f_τ$.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.grad_J_a_fluence — Function
Analytic derivative for J_a_fluence.
∇J_a = grad_J_a_fluence(pulsevals, tlist)returns ∇J_a, which contains the (vectorized) elements $2 ϵ_{nl} dt_n$, where $ϵ_{nl}$ are the (vectorized) elements of pulsevals and $dt_n =$ tlist[n+1] - tlist[n] is the duration of interval n. Supports non-uniform time grids.
QuantumControl.Functionals.f_tau — Function
Average complex overlap of the target states with forward-propagated states.
f_tau(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates
\[f_τ = \frac{1}{N} \sum_{k=1}^{N} w_k τ_k\]
with
\[τ_k = ⟨Ψ_k^\tgt|Ψ_k(T)⟩\]
in Hilbert space, or
\[τ_k = \tr[ρ̂_k^{\tgt\,\dagger} ρ̂_k(T)]\]
in Liouville space, where $|Ψ_k⟩$ or $ρ̂_k$ are the elements of Ψ, and $|Ψ_k^\tgt⟩$ or $ρ̂_k^\tgt$ are the target states from the target_state field of the trajectories. If tau/τ is given as a keyword argument, it must contain the values τ_k according to the above definition. Otherwise, the $τ_k$ values will be calculated internally, see taus.
$N$ is the number of trajectories, and $w_k$ is the weight attribute for each trajectory. The weights are not automatically normalized, they are assumed to have values such that the resulting $f_τ$ lies in the unit circle of the complex plane. Usually, this means that the weights should sum to $N$.
Reference
- [12] Palao and Kosloff, Phys. Rev. A 68, 062308 (2003)
QuantumControl.Functionals.chi_sm — Function
Backward boundary states $|χ⟩$ for functional J_T_sm.
χ = chi_sm(Ψ, trajectories; tau=taus(Ψ, trajectories), τ=tau)calculates the vector of states χ according to
\[|χ_k⟩ = -\frac{\partial J_{T,\text{sm}}}{\partial ⟨Ψ_k(T)|} = \frac{1}{N^2} w_k \sum_{j}^{N} w_j τ_j |Ψ_k^{\tgt}⟩\]
with $|Ψ^{\tgt}_k⟩$, $τ_j$ and $w_k$ as defined in f_tau.
Note: this function can be obtained with make_chi(J_T_sm, trajectories).
QuantumControl.Generators
Re-exported Symbols:
QuantumControl.Interfaces
Public Symbols:
Re-exported Symbols:
Public Symbols
QuantumControl.Interfaces.check_amplitude — Function
Check an amplitude in a Generator in the context of optimal control.
@test check_amplitude(
ampl; tlist, for_gradient_optimization=true, quiet=false
)verifies that the given ampl is a valid element in the list of amplitudes of a Generator object. This checks all the conditions of QuantumPropagators.Interfaces.check_amplitude. In addition, the following conditions must be met.
If for_gradient_optimization:
- The function
get_control_deriv(ampl, control)must be defined - If
ampldoes not depend oncontrol,get_control_deriv(ampl, control)must return0.0 - If
ampldepends oncontrol,u = get_control_deriv(ampl, control)must return an objectuso thatevaluate(u, tlist, n)returns a Number. In most cases,uitself will be a Number. For more unusual amplitudes, e.g., an amplitude with a non-linear dependency on the controls,umay be another amplitude. The controls inu(as obtained byQuantumPropagators.Controls.get_controls) must be a subset of the controls inampl.
The function returns true for a valid amplitude and false for an invalid amplitude. Unless quiet=true, it will log an error to indicate which of the conditions failed.
QuantumControl.Interfaces.check_control — Function
Check a control in the context of optimal control.
@test check_control(
control;
tlist,
for_parameterization=true,
for_time_continuous=(control isa Function),
for_gradient_optimization=true,
for_hessian=false,
quiet=false
)verifies the given control (one of the elements of the tuple returned by get_controls). This checks all the conditions of QuantumPropagators.Interfaces.check_control. In addition, the following conditions must be met.
If for_parameterization and for_gradient_optimization: for every index i of the parameter block p that control holds (if any), the derivative d = get_parameter_deriv(control, p, i) must be defined, and
dmust be a number, or passcheck_control(withfor_gradient_optimization=for_hessian)dmust hold no parameter block other thanp, i.e., the blocksget_parameters(d).xmust be empty or(p,)evaluate(d, tlist, n)must agree with the central finite difference ofevaluate(control, tlist, n)with respect top[i], for all intervalsnoftlist. The finite difference is obtained by mutatingp[i], and the original value is restored afterwards.- After changing the values in
p,evaluate(d, tlist, n)must again agree with the finite difference. This ensures thatdreads the parameter values when it is evaluated, not when it is created. - If the value of
dchanges with the values inp,dmust holdp, i.e.,get_parameters(d)must not be empty.
Also, for a block that control does not hold, get_parameter_deriv(control, block, i) must return 0.0.
If for_hessian (in addition to for_parameterization and for_gradient_optimization), every derivative d that is not a number must in turn have parameter derivatives that pass the above checks. Second derivatives are optional, so the default is for_hessian=false.
The function returns true for a valid control and false for an invalid control. Unless quiet=true, it will log an error to indicate which of the conditions failed.
QuantumControl.Interfaces.check_generator — Function
Check the dynamical generator in the context of optimal control.
@test check_generator(
generator; state, tlist,
for_expval=true, for_pwc=true, for_time_continuous=false,
for_parameterization=false, for_gradient_optimization=true,
for_hessian=false, atol=1e-15, quiet=false
)verifies the given generator. This checks all the conditions of QuantumPropagators.Interfaces.check_generator. In addition, the following conditions must be met.
If for_gradient_optimization:
get_control_derivs(generator, controls)must be defined and return a vector containing the result ofget_control_deriv(generator, control)for everycontrolincontrols.get_control_deriv(generator, control)must return an object that passes the less restrictiveQuantumPropagators.Interfaces.check_generatorifcontrolis inget_controls(generator). The controls in the derivative (if any) must be a subset of the controls ingenerator.get_control_deriv(generator, control)must returnnothingifcontrolis not inget_controls(generator)- If
generatoris aGeneratorinstance, everyamplingenerator.amplitudesmust passcheck_amplitude(ampl; tlist).
If for_parameterization and for_gradient_optimization:
- Every control in
get_controls(generator)must passcheck_controlwithfor_parameterization,for_gradient_optimization, andfor_hessian. derivs = get_parameter_derivs(generator, u)for the parametersu = get_parameters(generator)must be defined and return a vector of the same length asu.- Every element of
derivsthat is notnothingmust passQuantumPropagators.Interfaces.check_generatorwithfor_parameterization=true, and its parameter blocks must be blocks ofgenerator. - Every element
derivs[n]applied tostatemust agree with the central finite difference ofevaluate(generator, tlist, n) * statewith respect tou[n]for all intervals oftlist, whereevaluate(nothing, tlist, n)is taken as zero. The finite difference is obtained by mutatingu[n], and the original value is restored afterwards. - After changing the values in
u, every element ofderivsmust again agree with the finite difference. This ensures that the derivatives read the parameter values when they are evaluated, not when they are created. - For a block that
generatorneither holds nor inherits,get_parameter_deriv(generator, block, i)must returnnothing.
If for_hessian (in addition to for_parameterization and for_gradient_optimization), every element of derivs that is not nothing must in turn pass check_generator with for_parameterization=true and for_gradient_optimization=true, i.e., the second derivatives must agree with the finite differences of the first derivatives. Second derivatives are optional, so the default is for_hessian=false.
The function returns true for a valid generator and false for an invalid generator. Unless quiet=true, it will log an error to indicate which of the conditions failed.
QuantumControl.PulseParameterizations
Public Symbols:
LogisticParameterizationLogisticSqParameterizationParameterizedAmplitudeSquareParameterizationTanhParameterizationTanhSqParameterization
Private Symbols:
Public Symbols
QuantumControl.PulseParameterizations.LogisticParameterization — Function
Parameterization with a Logistic function that enforces a_min < a(t) < a_max.
QuantumControl.PulseParameterizations.LogisticSqParameterization — Function
Parameterization with a Logistic-Square function that enforces 0 ≤ a(t) < a_max.
QuantumControl.PulseParameterizations.ParameterizedAmplitude — Type
An amplitude determined by a pulse parameterization.
That is, $a(t) = a(ϵ(t))$ with a bijective mapping between the value of $a(t)$ and $ϵ(t)$, e.g. $a(t) = ϵ^2(t)$ (a SquareParameterization). Optionally, the amplitude may be multiplied with an additional shape function, cf. ShapedAmplitude.
ampl = ParameterizedAmplitude(control; parameterization)initializes $a(t) = a(ϵ(t)$ where $ϵ(t)$ is the control, and the mandatory keyword argument parameterization is a PulseParameterization. The control must either be a vector of values discretized to the midpoints of a time grid, or a callable control(t).
ampl = ParameterizedAmplitude(control; parameterization, shape=shape)initializes $a(t) = S(t) a(ϵ(t))$ where $S(t)$ is the given shape. It must be a vector if control is a vector, or a callable shape(t) if control is a callable.
ampl = ParameterizedAmplitude(control, tlist; parameterization, shape=shape)discretizes control and shape (if given) to the midpoints of tlist before initialization.
ampl = ParameterizedAmplitude(
amplitude, tlist; parameterization, shape=shape, parameterize=true
)initializes $ã(t) = S(t) a(t)$ where $a(t)$ is the input amplitude. First, if amplitude is a callable amplitude(t), it is discretized to the midpoints of tlist. Then, a control $ϵ(t)$ is calculated so that $a(t) ≈ a(ϵ(t))$. Clippling may occur if the values in amplitude cannot represented with the given parameterization. Lastly, ParameterizedAmplitude(control; parameterization, shape) is initialized with the calculated control.
Note that the tlist keyword argument is required when parameterize=true is given, even if amplitude is already a vector.
QuantumControl.PulseParameterizations.SquareParameterization — Function
Parameterization a(t) = ϵ²(t), enforcing pulse values $a(t) ≥ 0$.
QuantumControl.PulseParameterizations.TanhParameterization — Function
Parameterization with a tanh function that enforces a_min < a(t) < a_max.
QuantumControl.PulseParameterizations.TanhSqParameterization — Function
Parameterization with a tanh² function that enforces 0 ≤ a(t) < a_max.
Private Symbols
QuantumControl.PulseParameterizations.PulseParameterization — Type
Specification for a "time-local" pulse parameterization.
The parameterization is given as a collection of three functions:
- $a(ϵ(t))$
- $ϵ(a(t))$
- $∂a/∂ϵ$ as a function of $ϵ(t)$.
QuantumControl.Shapes
Re-exported Symbols:
QuantumControl.Storage
Re-exported Symbols:
QuantumControl.Workflows
Public Symbols:
Public Symbols
QuantumControl.Workflows.@optimize_or_load — Macro
Run optimize and store the result, or load the result if it exists.
result = @optimize_or_load(
file,
problem;
method,
force=false,
verbose=true,
metadata=nothing,
logfile=nothing,
kwargs...
)runs result = optimize(problem; method, kwargs...) and stores result in file in the JLD2 format. Note that the method keyword argument is mandatory.
In addition to the result, the data in the output file can also contain metadata. By default, this is "script" with the file name and line number of where @optimize_or_load was called, as well as data from the dict metadata mapping arbitrary (string) keys to values. Lastly, the data contains truncated captured output (up to 1kB of both the beginning and end of the output) from the optimization.
If logfile is given as the path to a file, both stdout and stderr from optimize are redirected into the given file.
If file already exists (and force=false), load the result from that file instead of running the optimization, and print any (truncated) captured output.
All other kwargs are passed directly to optimize.
For methods that support this, @optimize_or_load will set up a callback to dump the optimization result to file in case of an unexpected program shutdown, see set_atexit_save_optimization.
Related Functions
run_or_load— a function for more general long-running calculations.load_optimization: Function to load a file produced by@optimize_or_load
QuantumControl.Workflows.load_optimization — Function
Load a previously stored optimization.
result = load_optimization(file; verbose=false, kwargs...)recovers a result previously stored by @optimize_or_load or save_optimization.
result, metadata = load_optimization(file; return_metadata=true, kwargs...)also obtains a metadata dict, see @optimize_or_load. This dict maps string keys to values.
Calling load_optimization with verbose=true will @info the metadata after loading the file
QuantumControl.Workflows.run_or_load — Function
Run some code and write the result to file, or load from the file if it exists.
data = run_or_load(
file;
save=(endswith(file, ".jld2") ? JLD2.save_object : FileIO.save),
load=(endswith(file, ".jld2") ? JLD2.load_object : FileIO.load),
force=false,
verbose=true,
kwargs...
) do
data = Dict() # ... # something that can be saved to / loaded from file
return data
endruns the code in the block and stores data in the given file. If file already exists, skip running the code and instead return the data in file.
If force is True, run the code whether or not file exists, potentially overwriting it.
With verbose=true, information about the status of file will be shown as @info.
The data returned by the code block must be compatible with the format of file and the save/load functions. When using JLD2.save_object and JLD2.load_object, almost any data can be written, so this should be particularly safe. More generally, when using FileIO.save and FileIO.load, see the FileIO registry for details. A common examples would be a DataFrame being written to a .csv file.
See also
@optimize_or_load— for wrapping aroundoptimizeDrWatson.@produce_or_load— a similar but more opinionated function with automatic naming
QuantumControl.Workflows.save_optimization — Function
Write an optimization result to file.
save_optimization(file, result; metadata=nothing)writes the result obtained from a call to optimize to the given file in JLD2 format. If given, metadata is a dict of additional data that will be stored with the result. The metadata dict should use strings as keys.
See also
load_optimization: Function to load a file produced by@optimize_or_loadorsave_optimization@optimize_or_load: Runoptimizeandsave_optimizationin one go.
QuantumControl.DummyOptimization
The QuantumControl.DummyOptimization module is experimental. It is not part of the public API and is not covered by semantic versioning.
Private Symbols:
Private Symbols
QuantumControl.DummyOptimization.optimize_with_dummy_method — Function
Run a dummy optimization.
result = optimize(problem, method=:dummymethod)runs through and "optimization" of the given problem where in each iteration, the amplitude of the guess pulses is diminished by 10%. The (summed) vector norm of the the control serves as the value of the optimization functional.
QuantumControl.DummyOptimization.DummyOptimizationResult — Type
Result returned by optimize_with_dummy_method.
QuantumControl.DummyOptimization.dummy_control_problem — Function
Set up a dummy control problem.
problem = dummy_control_problem(;
N=10, n_trajectories=1, n_controls=1, n_steps=50, dt=1.0, density=0.5,
complex_operators=true, hermitian=true, pulses_as_controls=false, rng,
kwargs...)Sets up a control problem with random (sparse) Hermitian matrices.
Arguments
N: The dimension of the Hilbert spacen_trajectories: The number of trajectories in the optimization. All trajectories will have the same Hamiltonian, but random initial and target states.n_controls: The number of controls, that is, the number of control terms in the control Hamiltonian. Each control is an array of random values, normalized on the intervals of the time grid.n_steps: The number of time steps (intervals of the time grid)dt: The time stepdensity: The density of the Hamiltonians, as a number between 0.0 and 1.0. Fordensity=1.0, the Hamiltonians will be dense matrices.complex_operators: Whether or not the drift/control operators will be complex-valued or real-valued.hermitian: Whether or not all drift/control operators will be Hermitian matrices.pulses_as_controls=false: If true, directly use pulses (discretized to the midpoints of the time grid) as controls, instead of the normal controls discretized to the points of the time grid.rng=Random.GLOBAL_RNG: The random number generator to use. For a givenrng, the random matrices and states are the same as those fromrandom_matrixandrandom_state_vectorinQuantumControlTestUtils.kwargs: All other keyword arguments are passed on toQuantumControl.ControlProblem