CUDA-Q Python API¶
Program Construction¶
- cudaq.make_kernel(*args)¶
Create a
Kernel: An empty kernel function to be used for quantum program construction. This kernel is non-parameterized if it accepts no arguments, else takes the provided types as arguments.Returns a kernel if it is non-parameterized, else a tuple containing the kernel and a
QuakeValuefor each kernel argument.# Example: # Non-parameterized kernel. kernel = cudaq.make_kernel() # Example: # Parameterized kernel that accepts an `int` and `float` as arguments. kernel, int_value, float_value = cudaq.make_kernel(int, float)
- class cudaq.PyKernel(argTypeList)¶
The
Kernelprovides an API for dynamically constructing quantum circuits. TheKernelprogrammatically represents the circuit as an MLIR function using the Quake dialect.- arguments¶
The arguments accepted by the
Kernelfunction. Read-only.- Type:
List[
QuakeValue]
- class cudaq.PyKernelDecorator(function, verbose=False, defer_compilation=True, module=None, kernelName=None, signature=None, location=None, overrideGlobalScopedVars=None, decorator=None)¶
The
PyKernelDecoratorserves as a standard Python decorator that takes the decorated function as input. The function AST is parsed and converted to a Quake MLIR representation. This is passed on to the CUDAQ runtime for execution at kernel call time.By default, MLIR compilation is deferred until the first call to the kernel. If
defer_compilationis set toFalse, the kernel will be compiled at declaration time instead.- __call__(*args)¶
Invoke the CUDA-Q kernel. JIT compilation of the kernel AOT Quake module to machine code will occur here.
- __str__()¶
Return a string representation for this kernel as MLIR.
- beta_reduction(isEntryPoint, *args)¶
Perform beta reduction on this kernel decorator in the current calling context. We are primary concerned with resolving the lambda lifted arguments, but the formal arguments may be supplied as well.
This beta reduction may happen in a context that is earlier than the actual call to the decorator. While this loses some of Python’s intrinsic dynamism, it allows Python kernels to be specialized and passed to algorithms written in C++ that call back to these Python kernels in a functional composition.
- captured_variables()¶
The list of variables captured by the kernel.
- compile()¶
Compile the Python AST to portable Quake.
- enable_return_to_log()¶
Enable translation from
returnstatements to QIR output log
- static from_json(jStr, overrideDict=None)¶
Convert a JSON string into a new PyKernelDecorator object.
- is_compiled()¶
Whether the kernel has already been compiled.
- launch_args_required()¶
This is a deeper query on the quake module. The quake module may have been specialized such that none of the arguments are, in fact, required to be provided in order to run the kernel. (Argument synthesis.)
This will analyze the designated entry-point kernel for the quake module and determine if any arguments are used and return the number used.
- merge_kernel(otherMod)¶
Merge the kernel in this PyKernelDecorator (the ModuleOp) with the provided ModuleOp.
- merge_quake_source(quakeText)¶
Merge a module of quake code from source text form into this decorator’s
qkeModuleattribute.
- prepare_call(*args, allow_no_args=False)¶
Process call site arguments, capture lifted arguments and retrieve compiled module for kernel execution.
# Returns:
processed_argslistThe list of processed runtime arguments, including captured arguments,
moduleModuleA clone of the MLIR module to be used for kernel execution.
- process_call_arguments(*args, allow_no_args=False)¶
Resolve the arguments passed to the decorator at call site.
- property qkeModule¶
A target independent Quake MLIR representation of the kernel.
- resolve_captured_arguments()¶
Resolve the captured arguments of the decorator.
These arguments get resolved in the scope of the kernel definition (lexical scoping).
- signatureWithCallables()¶
returns True if and only if the entry-point contains callable arguments and/or return values.
- supports_compilation()¶
Whether the kernel can be compiled for the current target.
- to_json()¶
Convert
selfto a JSON-serialized version of the kernel such thatfrom_jsoncan reconstruct it elsewhere.
- static type_to_str(t)¶
This converts types to strings in a clean JSON-compatible way. int -> ‘int’ list[float] -> ‘list[float]’ List[float] -> ‘list[float]’
- cudaq.kernel(function=None, **kwargs)¶
The
cudaq.kernelrepresents the CUDA-Q language function attribute that programmers leverage to indicate the following function is a CUDA-Q kernel and should be compile and executed on an available quantum coprocessor.Verbose logging can be enabled via
verbose=True.
Kernel Execution¶
- cudaq.sample(kernel, *args, shots_count=1000, noise_model=None, explicit_measurements=False)¶
Sample the state generated by the provided
kernelat the given kernelargumentsover the specified number of circuit executions (shots_count). Each argument inargumentsprovided can be a list orndarrayof arguments of the specified kernel argument type, and in this case, thesamplefunctionality will be broadcasted over all argument sets and a list ofsample_resultinstances will be returned.- Parameters:
kernel (
Kernel) – TheKernelto executeshots_counttimes on the QPU.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments. For example, if the kernel takes two
floatvalues as input, thesamplecall should be structured ascudaq.sample(kernel, firstFloat, secondFloat). For broadcasting of thesamplefunction, the arguments should be structured as alistorndarrayof argument values of the specified kernel argument type.shots_count (Optional[int]) – The number of kernel executions on the QPU. Defaults to 1000. Key-word only.
noise_model (Optional[
NoiseModel]) – The optionalNoiseModelto add noise to the kernel execution on the simulator. Defaults to an empty noise model.explicit_measurements (Optional[bool]) – Whether or not to concatenate measurements in execution order for the returned sample result.
- Returns:
- A dictionary containing
the measurement count results for the
Kernel, or a list of such results in the case ofsamplefunction broadcasting.
- Return type:
SampleResultorlist[SampleResult]
- cudaq.sample_async(decorator, *args, shots_count=1000, explicit_measurements=False, noise_model=None, qpu_id=0)¶
Asynchronously sample the state of the provided kernel
decoratorat the specified number of circuit executions (shots_count). When targeting a quantum platform with more than one QPU, the optionalqpu_idallows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get().- Parameters:
kernel (
Kernel) – TheKernelto executeshots_counttimes on the QPU.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
shots_count (Optional[int]) – The number of kernel executions on the QPU. Defaults to 1000. Key-word only.
explicit_measurements (Optional[bool]) – A flag to indicate whether or not to concatenate measurements in execution order for the returned sample result.
noise_model (Optional[
NoiseModel]) – The optionalNoiseModelto add noise to the kernel execution on the simulator. Defaults to an empty noise model.qpu_id (Optional[int]) – The optional identification for which QPU on the platform to target. Defaults to zero. Key-word only.
- Returns:
- A dictionary containing the measurement count
results for the
Kernel.
- Return type:
- cudaq.run(decorator, *args, shots_count=100, noise_model=None, qpu_id=0)¶
- cudaq.run_async(decorator, *args, shots_count=100, noise_model=None, qpu_id=0)¶
Run the provided
kernelwith the given kernelargumentsover the specified number of circuit executions (shots_count) asynchronously on the specifiedqpu_id.- Parameters:
kernel (
Kernel) – TheKernelto executeshots_counttimes on the QPU.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments. For example, if the kernel takes two
floatvalues as input, theruncall should be structured ascudaq.run(kernel, firstFloat, secondFloat).shots_count (Optional[int]) – The number of kernel executions on the QPU. Defaults to 100. Key-word only.
noise_model (Optional[
NoiseModel]) – The optionalNoiseModelto add noise to the kernel execution on the simulator. Defaults to an empty noise model.qpu_id (Optional[int]) – The id of the QPU. Defaults to 0. Key-word only.
- Returns:
A handle, which can be waited on via a
get()method, which returns an array ofkernelreturn values. The length of the list is equal toshots_count.- Return type:
AsyncRunResult
- cudaq.observe(kernel, spin_operator, *args, shots_count=0, noise_model=None, num_trajectories=None, execution=None, qpu_id=0)¶
Compute the expected value of the
spin_operatorwith respect to thekernel. If the inputspin_operatoris a list ofSpinOperatorthen compute the expected value of every operator in the list and return a list of results. If the kernel accepts arguments, it will be evaluated with respect tokernel(*arguments). Each argument inargumentsprovided can be a list orndarrayof arguments of the specified kernel argument type, and in this case, theobservefunctionality will be broadcasted over all argument sets and a list ofobserve_resultinstances will be returned. If both the inputspin_operatorandargumentsare broadcast lists, a nested list of results overargumentsthenspin_operatorwill be returned.- Parameters:
kernel (
Kernel) – TheKernelto evaluate the expectation value with respect to.spin_operator (
SpinOperatororlist[SpinOperator]) – The Hermitian spin operator to calculate the expectation of, or a list of such operators.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
shots_count (Optional[int]) – The number of shots to use for QPU execution. Defaults to -1 implying no shots-based sampling. Key-word only.
noise_model (Optional[
NoiseModel]) – The optionalNoiseModelto add noise to the kernel execution on the simulator. Defaults to an empty noise model.num_trajectories (Optional[int]) – The optional number of trajectories for noisy simulation. Only valid if a noise model is provided.
Keywordonly.qpu_id (Optional[int]) – The id of the QPU. Defaults to 0. Key-word only.
- Returns:
A data-type containing the expectation value of the
spin_operatorwith respect to thekernel(*arguments), or a list of such results in the case ofobservefunction broadcasting. Ifshots_countwas provided, theObserveResultwill also contain aSampleResultdictionary.- Return type:
- cudaq.observe_async(kernel, spin_operator, *args, qpu_id=0, shots_count=-1)¶
Compute the expected value of the
spin_operatorwith respect to thekernelasynchronously. If the kernel accepts arguments, it will be evaluated with respect tokernel(*arguments). When targeting a quantum platform with more than one QPU, the optionalqpu_idallows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get().- Parameters:
kernel (
Kernel) – TheKernelto evaluate the expectation value with respect to.spin_operator (
SpinOperator) – The Hermitian spin operator to calculate the expectation of.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
qpu_id (Optional[int]) – The optional identification for which QPU on the platform to target. Defaults to zero. Key-word only.
shots_count (Optional[int]) – The number of shots to use for QPU execution. Defaults to -1 implying no shots-based sampling. Key-word only.
- Returns:
- A future containing the result of the call
to observe.
- Return type:
- cudaq.get_state(kernel, *args)¶
Return the
Stateof the system after execution of the providedkernel.- Parameters:
# Example:
import numpy as np# Define a kernel that will produced the all
|11...1>state.qubits = kernel.qalloc(3)# Prepare qubits in the 1-state. kernel.x(qubits)Get the state of the system. This will execute the provided kernel # and, depending on the selected target, will return the state as a # vector or matrix. state = cudaq.get_state(kernel) print(state)
- cudaq.get_state_async(kernel, *args, qpu_id=0)¶
Asynchronously retrieve the state generated by the given quantum kernel. When targeting a quantum platform with more than one QPU, the optional
qpu_idallows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get().- Parameters:
*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
qpu_id (Optional[int]) – The optional identification for which QPU on the platform to target. Defaults to zero. Key-word only.
- Returns:
- Quantum state data. (state vector or density
matrix)
- Return type:
- cudaq.vqe(*args, kernel=None, gradient_strategy=None, spin_operator=None, optimizer=None, parameter_count=None, argument_wrapper=None, shots=None)¶
- cudaq.draw(decoratorOrFormat, *args)¶
The CUDA-Q specification overloads draw. To meet that, this function uses parameter type checking. The two overloads for
cudaq.draware:` python cudaq.draw("<format>", kernel, opt_args...) cudaq.draw(kernel, opt_args...) `The second overload is equivalent to using a format string of"ascii".
- cudaq.translate(kernel, *args, format='qir:0.1')¶
Return a
UTF-8encoded string representing drawing of the execution path, i.e., the trace, of the providedkernel.- Parameters:
format (
str) – format to translate to, <name[:version]>. Available format names:qir,qir-full,qir-base,qir-adaptive,openqasm2. QIR versions:0.1and1.0.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
Note: Translating functions with arguments to OpenQASM 2.0 is not supported.
- Returns:
The
UTF-8encoded string of the circuit, without measurement operations.
# Example: import cudaq @cudaq.kernel def bell_pair():
q = cudaq.qvector(2)h(q[0])cx(q[0], q[1])mz(q)print(cudaq.translate(bell_pair,format="qir"))# Output
; ModuleID = 'LLVMDialectModule'source_filename = 'LLVMDialectModule'%Array = type opaque %Result = type opaque %Qubit = type opaque
…¶
define void
@__nvqpp__mlirgen__function_variable_qreg._Z13variable_qregv`() `local_unnamed_addr{ %1 = tail call %Array* @__quantum__rt__qubit_allocate_array(i64 2) … %8 = tail call %Result* @`__quantum__qis__mz`(%Qubit* %4) %9 = tail call %Result* @`__quantum__qis__mz`(%Qubit* %7) tail call void @`__quantum__rt__qubit_release_array`(%Array* %1)ret void}
- cudaq.estimate_resources(kernel, *args, **kwargs)¶
Performs resource counting on the given quantum kernel expression and returns an accounting of how many times each gate was applied, in addition to the total number of gates and qubits used.
- Parameters:
choice (Any) – A choice function called to determine the outcome of measurements, in case control flow depends on measurements. Should only return either
TrueorFalse. Invoking the kernel within the choice function is forbidden. Default: returnsTrueorFalsewith 50% probability.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
- Returns:
- A dictionary containing the resource count results
for the
Kernel.
- Return type:
Backend Configuration¶
- cudaq.parse_args(args: Optional[Sequence[str]] = None)¶
Parse command line arguments and initialize the CUDA-Q environment.
- cudaq.get_target(arg: str, /) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target¶
- cudaq.get_target() cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target
Return the
cudaq.Targetwith the given name. Will raise an exception if the name is not valid.
- cudaq.get_targets() list[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target]¶
Return all available
cudaq.Targetinstances on the current system.
- cudaq.set_target(arg0: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target, /, **kwargs) None¶
- cudaq.set_target(arg0: str, /, **kwargs) None
Overloaded function.
set_target(arg0: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target, /, **kwargs) -> None
Set the
cudaq.Targetto be used for CUDA-Q kernel execution. Can provide optional, target-specific configuration data via Python kwargs.set_target(arg0: str, /, **kwargs) -> None
Set the
cudaq.Targetwith given name to be used for CUDA-Q kernel execution. Can provide optional, target-specific configuration data via Python kwargs.
- cudaq.set_noise(arg: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.NoiseModel, /) None¶
Set the underlying noise model.
- cudaq.register_set_target_callback(arg0: collections.abc.Callable[[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target], None], arg1: str, /) None¶
Register a callback function to be executed when the runtime target is changed. The string
idcan be used to identify the callback for replacement/removal purposes.
- cudaq.unregister_set_target_callback(arg: str, /) None¶
Unregister a callback identified by the input identifier.
- cudaq.apply_noise(error_type, parameters..., targets...)¶
This function is a type-safe injection of noise into a quantum kernel, occurring precisely at the call site of the function invocation. The function should be called inside CUDA-Q kernels (those annotated with
@cudaq.kernel). The functionality is only supported for simulation targets, so it is automatically (and silently) stripped from any programs submitted to hardware targets.- Parameters:
error_type –
A subtype of
cudaq.KrausChannelthat implements/defines the desired noise mechanisms as Kraus channels (e.g.cudaq.Depolarization2). If you want to use a customcudaq.KrausChannel(i.e. not built-in to CUDA-Q), it must first be registered outside the kernel withregister_channel, like this:class CustomNoiseChannel(cudaq.KrausChannel): num_parameters = 1 num_targets = 1 def __init__(self, params: list[float]): cudaq.KrausChannel.__init__(self) # Example: Create Kraus ops based on params p = params[0] k0 = np.array([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]], dtype=np.complex128) k1 = np.array([[0, np.sqrt(p)], [np.sqrt(p), 0]], dtype=np.complex128) # Create KrausOperators and add to channel self.append(cudaq.KrausOperator(k0)) self.append(cudaq.KrausOperator(k1)) self.noise_type = cudaq.NoiseModelType.Unknown noise = cudaq.NoiseModel() noise.register_channel(CustomNoiseChannel)
parameters –
The precise argument pack depend on the concrete
cudaq.KrausChannelbeing used. The arguments are a concatenated list of parameters and targets. For example, to apply a 2-qubit depolarization channel, which hasnum_parameters = 1andnum_targets = 2, one would write the call like this:q, r = cudaq.qubit(), cudaq.qubit() cudaq.apply_noise(cudaq.Depolarization2, 0.1, q, r)
targets – The target qubits on which to apply the noise
Dynamics¶
- cudaq.evolve(hamiltonian: Union[MatrixOperator, SpinOperator, BosonOperator, FermionOperator, MatrixOperatorTerm, SpinOperatorTerm, BosonOperatorTerm, FermionOperatorTerm, ScalarOperator, SuperOperator, Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator], Sequence[SuperOperator]], dimensions: Mapping[int, int] = {}, schedule: Schedule = None, initial_state: Union[State, InitialStateType, Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.InitialStateType]] = None, collapse_operators: Union[Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator], Sequence[Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator]]] = [], observables: Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator] = [], store_intermediate_results: cudaq.dynamics.helpers.IntermediateResultSave | bool = IntermediateResultSave.NONE, integrator: Optional[BaseIntegrator] = None, shots_count: Optional[int] = None, max_batch_size: Optional[int] = None) Union[EvolveResult, Sequence[EvolveResult]]¶
Computes the time evolution of one or more initial state(s) under the defined operator(s).
- Parameters:
hamiltonian – Operator that describes the behavior of a quantum system without noise.
dimensions – A mapping that specifies the number of levels, that is the dimension, of each degree of freedom that any of the operator arguments acts on.
schedule – A sequence that generates a mapping of keyword arguments to their respective value. The keyword arguments are the parameters needed to evaluate any of the operators passed to
evolve. All required parameters for evaluating an operator and their documentation, if available, can be queried by accessing theparameterproperty of the operator.initial_state – A single state or a sequence of states of a quantum system.
collapse_operators – A sequence of operators that describe the influence of noise on the quantum system.
observables – A sequence of operators for which to compute their expectation value during evolution. If
store_intermediate_resultsis not None, the expectation values are computed after each step in the schedule, and otherwise only the final expectation values at the end of the evolution are computed.shots_count – Optional integer, if provided, it is the number of shots to use for QPU execution.
- Returns:
A single evolution result if a single initial state is provided, or a sequence of evolution results representing the data computed during the evolution of each initial state. See
EvolveResultfor more information about the data computed during evolution.
- cudaq.evolve_async(hamiltonian: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator, dimensions: Mapping[int, int] = {}, schedule: Schedule = None, initial_state: Union[State, InitialStateType, Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.InitialStateType]] = None, collapse_operators: Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator] = [], observables: Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm | cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator] = [], store_intermediate_results: cudaq.dynamics.helpers.IntermediateResultSave | bool = IntermediateResultSave.NONE, integrator: Optional[BaseIntegrator] = None, shots_count: Optional[int] = None) Union[AsyncEvolveResult, Sequence[AsyncEvolveResult]]¶
Asynchronously computes the time evolution of one or more initial state(s) under the defined operator(s). See
cudaq.evolvefor more details about the parameters passed here.- Returns:
The handle to a single evolution result if a single initial state is provided, or a sequence of handles to the evolution results representing the data computed during the evolution of each initial state. See the
EvolveResultfor more information about the data computed during evolution.
- class cudaq.Schedule(steps: Iterable[Any], parameters: Iterable[str], get_value: Optional[Callable[[str, Any], numpy.complexfloating | complex | float | int]] = None)¶
Represents an iterator that produces all values needed for evaluating an operator expression at different time steps.
- class cudaq.dynamics.integrator.BaseIntegrator(**kwargs)¶
An abstract wrapper around ODE integrator to ensure a common interface for master equation solver usage.
- cudaq.dynamics.helpers.InitialState¶
alias of
InitialStateType
- class cudaq.InitialStateType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Enumeration describing the initial state type to be created in the backend
- class cudaq.IntermediateResultSave(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Enum to specify how intermediate results should be saved during the dynamics evolution.
Operators¶
- cudaq.operators.OperatorSum¶
alias of
MatrixOperator|SpinOperator|BosonOperator|FermionOperator
- cudaq.operators.ProductOperator¶
alias of
MatrixOperatorTerm|SpinOperatorTerm|BosonOperatorTerm|FermionOperatorTerm
- cudaq.operators.ElementaryOperator¶
alias of
SpinOperatorElement|BosonOperatorElement|FermionOperatorElement|MatrixOperatorElement
- class cudaq.operators.ScalarOperator(*args, **kwargs)¶
- classmethod const(constant_value: numpy.complexfloating | complex | float | int) ScalarOperator¶
Creates a scalar operator that has a constant value.
- evaluate¶
Evaluated value of the operator.
- is_constant¶
Returns true if the scalar is a constant value.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- to_matrix(dimensions: Mapping[int, int] = {}, **kwargs: numpy.complexfloating | complex | float | int) ndarray[Any, dtype[complexfloating]]¶
Class method for consistency with other operator classes. Invokes the generator with the given keyword arguments.
- Parameters:
dimensions – (unused, passed for consistency) A mapping that specifies the number of levels, that is the dimension, of each degree of freedom that the operator acts on.
kwargs – Keyword arguments needed to evaluate the generator. All required parameters and their documentation, if available, can be queried by accessing the
parameterproperty.
- Returns:
An array with a single element corresponding to the value of the operator for the given keyword arguments.
- class cudaq.operators.RydbergHamiltonian(atom_sites: Iterable[tuple[float, float]], amplitude: ScalarOperator, phase: ScalarOperator, delta_global: ScalarOperator, atom_filling: Optional[Iterable[int]] = [], delta_local: Optional[tuple[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator, Iterable[float]]] = None)¶
Representation for the time-dependent Hamiltonian which is simulated by analog neutral-atom machines such as QuEra’s Aquila and Pasqal’s Fresnel. Ref: https://docs.aws.amazon.com/braket/latest/developerguide/braket-quera-submitting-analog-program-aquila.html#braket-quera-ahs-program-schema
- __init__(atom_sites: Iterable[tuple[float, float]], amplitude: ScalarOperator, phase: ScalarOperator, delta_global: ScalarOperator, atom_filling: Optional[Iterable[int]] = [], delta_local: Optional[tuple[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ScalarOperator, Iterable[float]]] = None)¶
Instantiate an operator consumable by
evolveAPI using the supplied parameters.- Parameters:
atom_sites – List of 2-d coordinates where the tweezers trap atoms.
amplitude – time and value points of driving amplitude, Omega(t).
phase – time and value points of driving phase, phi(t).
delta_global – time and value points of driving detuning, Delta_global(t).
atom_filling – typing.Optional. Marks atoms that occupy the trap sites with 1, and empty sites with 0. If not provided, all are set to 1, i.e. filled.
delta_local – typing.Optional. A tuple of time and value points of the time-dependent factor of the local detuning magnitude, Delta_local(t), and site-dependent factor of the local detuning magnitude, h_k, a dimensionless number between 0.0 and 1.0
- class cudaq.SuperOperator(*args, **kwargs)¶
- left_multiply = <nanobind.nb_func object>¶
- left_right_multiply = <nanobind.nb_func object>¶
- right_multiply = <nanobind.nb_func object>¶
- operators.define(expected_dimensions: Sequence[int], create: Callable[[...], ndarray[Any, dtype[complexfloating]]], override: bool = False) None¶
Defines a matrix operator element with the given id. After definition, an the defined elementary operator can be instantiated by providing the operator id as well as the degree(s) of freedom that it acts on. A matrix operator element is a parameterized object acting on certain degrees of freedom. To evaluate an operator, for example to compute its matrix, the level, that is the dimension, for each degree of freedom it acts on must be provided, as well as all additional parameters. Additional parameters must be provided in the form of keyword arguments.
Note: The dimensions passed during operator evaluation are automatically validated against the expected dimensions specified during definition - the
createfunction does not need to do this.- Parameters:
op_id – A string that uniquely identifies the defined operator.
expected_dimensions – defines the number of levels, that is the dimension, for each degree of freedom in canonical (that is sorted) order. A negative or zero value for one (or more) of the expected dimensions indicates that the operator is defined for any dimension of the corresponding degree of freedom.
create – Takes any number of complex-valued arguments and returns the matrix representing the operator in canonical order. If the matrix can be defined for any number of levels for one or more degree of freedom, the
createfunction must take an argument calleddimension(ordimfor short), if the operator acts on a single degree of freedom, and an argument calleddimensions(ordimsfor short), if the operator acts on multiple degrees of freedom.override – if True it allows override the definition. (default: False)
- operators.instantiate(degrees: Union[int, Iterable[int]]) MatrixOperatorTerm¶
Instantiates a product operator containing a previously defined operator element.
- Parameters:
operator_id – The id of the operator element as specified when it was defined.
degrees – The degree(s) of freedom that the operator acts on.
Spin Operators¶
- class cudaq.operators.spin.SpinOperator(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator
Expands the operator to act on all given degrees, applying identities as needed. If an empty set is passed, canonicalizes all terms in the sum to act on the same degrees of freedom.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- distribute_terms¶
Partitions the terms of the sums into the given number of separate sums.
- dump¶
Prints the string representation of the operator to the standard output.
- empty = <nanobind.nb_func object>¶
- empty_op = <nanobind.nb_func object>¶
- for_each_pauli¶
Deprecated - iterator over sum and then iterator over term instead.
- for_each_term¶
Deprecated - use standard iteration instead.
- from_json = <nanobind.nb_func object>¶
- from_word = <nanobind.nb_func object>¶
- get_coefficient¶
Deprecated - use
evaluate_coefficienton each term (product operator) instead.
- get_qubit_count¶
Deprecated - use
qubit_countinstead.
- get_raw_data¶
Deprecated.
- get_term_count¶
Deprecated - use
term_countinstead.
- identity = <nanobind.nb_func object>¶
- is_identity¶
Deprecated - is_identity will only be supported on each term (product operator) in future releases.
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property qubit_count¶
Return the number of qubits this operator acts on.
- random = <nanobind.nb_func object>¶
- serialize¶
Returns the serialized data representation of the operator.
- property term_count¶
Returns the number of terms in the operator.
- to_json¶
Convert spin_op to a JSON string, e.g., ‘[d1, d2, d3, …]’.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_sparse_matrix¶
Return the sparse matrix representation of the operator. This representation is a
Tuple[list[complex], list[int], list[int]], encoding the non-zero values, rows, and columns of the matrix. This format is supported byscipy.sparse.csr_array.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned bydegrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_string¶
Deprecated - use the standard
strconversion orget_pauli_wordon each term instead.
- trim¶
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.spin.SpinOperatorTerm(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm
Expands the operator to act on all given degrees, applying identities as needed. The canonicalization will throw a runtime exception if the operator acts on any degrees of freedom that are not included in the given set.
- property coefficient¶
Returns the unevaluated coefficient of the operator. The coefficient is a callback function that can be invoked with the
evaluatemethod.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- distribute_terms¶
Deprecated - instantiate a
SpinOperatorfrom thisSpinOperatorTermand call distribute_terms on that.
- dump¶
Prints the string representation of the operator to the standard output.
- evaluate_coefficient¶
Returns the evaluated coefficient of the product operator. The parameters is a map of parameter names to their concrete, complex values.
- for_each_pauli¶
Deprecated - use standard iteration instead.
- from_json = <nanobind.nb_func object>¶
- get_binary_symplectic_form¶
Gets the binary symplectic representation of this operator.
- get_coefficient¶
Deprecated - use
evaluate_coefficientinstead.
- get_pauli_word¶
Gets the Pauli word representation of this product operator.
- get_qubit_count¶
Deprecated - use
qubit_countinstead.
- get_raw_data¶
Deprecated.
- is_identity¶
Checks if all operators in the product are the identity. Note that this function returns true regardless of the value of the coefficient.
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property ops_count¶
Returns the number of operators in the product.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property qubit_count¶
Return the number of qubits this operator acts on.
- serialize¶
Returns the serialized data representation of the operator.
- property term_count¶
Returns the number of terms in the operator. Always returns 1.
- property term_id¶
The term id uniquely identifies the operators and targets (degrees) that they act on, but does not include information about the coefficient.
- to_json¶
Convert spin_op to a JSON string, e.g., ‘[d1, d2, d3, …]’.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_sparse_matrix¶
Return the sparse matrix representation of the operator. This representation is a
Tuple[list[complex], list[int], list[int]], encoding the non-zero values, rows, and columns of the matrix. This format is supported byscipy.sparse.csr_array.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned bydegrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_string¶
Deprecated - use the standard
strconversion or useget_pauli_wordinstead.
- class cudaq.operators.spin.SpinOperatorElement(*args, **kwargs)¶
- as_pauli¶
Returns the Pauli representation of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets.
- property target¶
Returns the degree of freedom that the operator targets.
- to_matrix¶
Returns the matrix representation of the operator.
- to_string¶
Returns the string representation of the operator.
Fermion Operators¶
- class cudaq.operators.fermion.FermionOperator(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperator
Expands the operator to act on all given degrees, applying identities as needed. If an empty set is passed, canonicalizes all terms in the sum to act on the same degrees of freedom.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- distribute_terms¶
Partitions the terms of the sums into the given number of separate sums.
- dump¶
Prints the string representation of the operator to the standard output.
- empty = <nanobind.nb_func object>¶
- identity = <nanobind.nb_func object>¶
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property term_count¶
Returns the number of terms in the operator.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_sparse_matrix¶
Return the sparse matrix representation of the operator. This representation is a
Tuple[list[complex], list[int], list[int]], encoding the non-zero values, rows, and columns of the matrix. This format is supported byscipy.sparse.csr_array.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned bydegrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- trim¶
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.fermion.FermionOperatorTerm(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.FermionOperatorTerm
Expands the operator to act on all given degrees, applying identities as needed. The canonicalization will throw a runtime exception if the operator acts on any degrees of freedom that are not included in the given set.
- property coefficient¶
Returns the unevaluated coefficient of the operator. The coefficient is a callback function that can be invoked with the
evaluatemethod.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- dump¶
Prints the string representation of the operator to the standard output.
- evaluate_coefficient¶
Returns the evaluated coefficient of the product operator. The parameters is a map of parameter names to their concrete, complex values.
- is_identity¶
Checks if all operators in the product are the identity. Note that this function returns true regardless of the value of the coefficient.
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property ops_count¶
Returns the number of operators in the product.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property term_id¶
The term id uniquely identifies the operators and targets (degrees) that they act on, but does not include information about the coefficient.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_sparse_matrix¶
Return the sparse matrix representation of the operator. This representation is a
Tuple[list[complex], list[int], list[int]], encoding the non-zero values, rows, and columns of the matrix. This format is supported byscipy.sparse.csr_array.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned bydegrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- class cudaq.operators.fermion.FermionOperatorElement(*args, **kwargs)¶
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets.
- property target¶
Returns the degree of freedom that the operator targets.
- to_matrix¶
Returns the matrix representation of the operator.
- to_string¶
Returns the string representation of the operator.
Boson Operators¶
- class cudaq.operators.boson.BosonOperator(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperator
Expands the operator to act on all given degrees, applying identities as needed. If an empty set is passed, canonicalizes all terms in the sum to act on the same degrees of freedom.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- distribute_terms¶
Partitions the terms of the sums into the given number of separate sums.
- dump¶
Prints the string representation of the operator to the standard output.
- empty = <nanobind.nb_func object>¶
- identity = <nanobind.nb_func object>¶
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property term_count¶
Returns the number of terms in the operator.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_sparse_matrix¶
Return the sparse matrix representation of the operator. This representation is a
Tuple[list[complex], list[int], list[int]], encoding the non-zero values, rows, and columns of the matrix. This format is supported byscipy.sparse.csr_array.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned bydegrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- trim¶
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.boson.BosonOperatorTerm(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BosonOperatorTerm
Expands the operator to act on all given degrees, applying identities as needed. The canonicalization will throw a runtime exception if the operator acts on any degrees of freedom that are not included in the given set.
- property coefficient¶
Returns the unevaluated coefficient of the operator. The coefficient is a callback function that can be invoked with the
evaluatemethod.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- dump¶
Prints the string representation of the operator to the standard output.
- evaluate_coefficient¶
Returns the evaluated coefficient of the product operator. The parameters is a map of parameter names to their concrete, complex values.
- is_identity¶
Checks if all operators in the product are the identity. Note that this function returns true regardless of the value of the coefficient.
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property ops_count¶
Returns the number of operators in the product.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property term_id¶
The term id uniquely identifies the operators and targets (degrees) that they act on, but does not include information about the coefficient.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- to_sparse_matrix¶
Return the sparse matrix representation of the operator. This representation is a
Tuple[list[complex], list[int], list[int]], encoding the non-zero values, rows, and columns of the matrix. This format is supported byscipy.sparse.csr_array.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned bydegrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- class cudaq.operators.boson.BosonOperatorElement(*args, **kwargs)¶
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets.
- property target¶
Returns the degree of freedom that the operator targets.
- to_matrix¶
Returns the matrix representation of the operator.
- to_string¶
Returns the string representation of the operator.
General Operators¶
- class cudaq.operators.MatrixOperator(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperator
Expands the operator to act on all given degrees, applying identities as needed. If an empty set is passed, canonicalizes all terms in the sum to act on the same degrees of freedom.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets.
- distribute_terms¶
Partitions the terms of the sums into the given number of separate sums.
- dump¶
Prints the string representation of the operator to the standard output.
- empty = <nanobind.nb_func object>¶
- identity = <nanobind.nb_func object>¶
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property term_count¶
Returns the number of terms in the operator.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- trim¶
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.MatrixOperatorTerm(*args, **kwargs)¶
- canonicalize¶
Overloaded function.
canonicalize(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm
Removes all identity operators from the operator.
canonicalize(self, arg: collections.abc.Set[int], /) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.MatrixOperatorTerm
Expands the operator to act on all given degrees, applying identities as needed. The canonicalization will throw a runtime exception if the operator acts on any degrees of freedom that are not included in the given set.
- property coefficient¶
Returns the unevaluated coefficient of the operator. The coefficient is a callback function that can be invoked with the
evaluatemethod.
- copy¶
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets. The order of degrees is from smallest to largest and reflects the ordering of the matrix returned by
to_matrix. Specifically, the indices of a statevector with two qubits are {00, 01, 10, 11}. An ordering of degrees {0, 1} then indicates that a state where the qubit with index 0 equals 1 with probability 1 is given by the vector {0., 1., 0., 0.}.
- dump¶
Prints the string representation of the operator to the standard output.
- evaluate_coefficient¶
Returns the evaluated coefficient of the product operator. The parameters is a map of parameter names to their concrete, complex values.
- is_identity¶
Checks if all operators in the product are the identity. Note that this function returns true regardless of the value of the coefficient.
- property max_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property min_degree¶
Returns the smallest index of the degrees of freedom that the operator targets.
- property ops_count¶
Returns the number of operators in the product.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- property term_id¶
The term id uniquely identifies the operators and targets (degrees) that they act on, but does not include information about the coefficient.
- to_matrix¶
Returns the matrix representation of the operator.The matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees. This order can be inverted by setting the optionalinvert_orderargument toTrue. See also the documentation fordegreesfor more detail.
- class cudaq.operators.MatrixOperatorElement(*args, **kwargs)¶
- classmethod define(id: str, expected_dimensions: Sequence[int], create: Callable[[...], ndarray[Any, dtype[complexfloating]]], override: bool = False) None¶
Creates the definition of an elementary operator with the given id.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets.
- property expected_dimensions¶
The number of levels, that is the dimension, for each degree of freedom in canonical order that the operator acts on. A value of zero or less indicates that the operator is defined for any dimension of that degree.
- property id¶
Returns the id used to define and instantiate the operator.
- property parameters¶
Returns a dictionary that maps each parameter name to its description.
- to_matrix¶
Returns the matrix representation of the operator.
- to_string¶
Returns the string representation of the operator.
- cudaq.operators.custom.define(id: str, expected_dimensions: Sequence[int], create: Callable[[...], ndarray[Any, dtype[complexfloating]]], override: bool = False) None¶
Defines a matrix operator element with the given id. After definition, an the defined elementary operator can be instantiated by providing the operator id as well as the degree(s) of freedom that it acts on. A matrix operator element is a parameterized object acting on certain degrees of freedom. To evaluate an operator, for example to compute its matrix, the level, that is the dimension, for each degree of freedom it acts on must be provided, as well as all additional parameters. Additional parameters must be provided in the form of keyword arguments.
Note: The dimensions passed during operator evaluation are automatically validated against the expected dimensions specified during definition - the
createfunction does not need to do this.- Parameters:
op_id – A string that uniquely identifies the defined operator.
expected_dimensions – defines the number of levels, that is the dimension, for each degree of freedom in canonical (that is sorted) order. A negative or zero value for one (or more) of the expected dimensions indicates that the operator is defined for any dimension of the corresponding degree of freedom.
create – Takes any number of complex-valued arguments and returns the matrix representing the operator in canonical order. If the matrix can be defined for any number of levels for one or more degree of freedom, the
createfunction must take an argument calleddimension(ordimfor short), if the operator acts on a single degree of freedom, and an argument calleddimensions(ordimsfor short), if the operator acts on multiple degrees of freedom.override – if True it allows override the definition. (default: False)
- cudaq.operators.custom.instantiate(op_id: str, degrees: Union[int, Iterable[int]]) MatrixOperatorTerm¶
Instantiates a product operator containing a previously defined operator element.
- Parameters:
operator_id – The id of the operator element as specified when it was defined.
degrees – The degree(s) of freedom that the operator acts on.
Data Types¶
- class cudaq.SimulationPrecision(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Enumeration describing the precision of the underlying simulation.
- class cudaq.Target¶
The
cudaq.Targetrepresents the underlying infrastructure that CUDA-Q kernels will execute on. Instances ofcudaq.Targetdescribe what simulator they may leverage, the quantum_platform required for execution, and a description for the target.- property description¶
A string describing the features for this
cudaq.Target.
- get_precision¶
Return the simulation precision for the current target.
- is_emulated¶
Returns true if the emulation mode for the target has been activated.
- is_remote¶
Returns true if the target consists of a remote REST QPU.
- is_remote_simulator¶
Returns true if the target consists of a remote REST Simulator QPU.
- property name¶
The name of the
cudaq.Target.
- num_qpus¶
Return the number of QPUs available in this
cudaq.Target.
- property platform¶
The name of the quantum_platform implementation this
cudaq.Targetleverages.
- property simulator¶
The name of the simulator this
cudaq.Targetleverages. This will be empty for physical QPUs.
- class cudaq.State¶
A data-type representing the quantum state of the internal simulator. This type is not user-constructible and instances can only be retrieved via the
cudaq.get_state(...)function or the staticcudaq.State.from_data()method.- amplitude¶
Overloaded function.
amplitude(self, arg: collections.abc.Sequence[int], /) -> complex
Return the amplitude of a state in computational basis.
# Example: # Create a simulation state. state = cudaq.get_state(kernel) # Return the amplitude of |0101>, assuming this is a 4-qubit state. amplitude = state.amplitude([0,1,0,1])
amplitude(self, arg: str, /) -> complex
Return the amplitude of a state in computational basis.
# Example: # Create a simulation state. state = cudaq.get_state(kernel) # Return the amplitude of |0101>, assuming this is a 4-qubit state. amplitude = state.amplitude('0101')
- amplitudes¶
Overloaded function.
amplitudes(self, arg: collections.abc.Sequence[collections.abc.Sequence[int]], /) -> list[complex]
Return the amplitude of a list of states in computational basis.
# Example: # Create a simulation state. state = cudaq.get_state(kernel) # Return the amplitude of |0101> and |1010>, assuming this is a 4-qubit state. amplitudes = state.amplitudes([[0,1,0,1], [1,0,1,0]])
amplitudes(self, arg: collections.abc.Sequence[str], /) -> list[complex]
Return the amplitudes of a list of states in computational basis.
# Example: # Create a simulation state. state = cudaq.get_state(kernel) # Return the amplitudes of |0101> and |1010>, assuming this is a 4-qubit state. amplitudes = state.amplitudes(['0101', '1010'])
- dump¶
Print the state to the console.
- from_data = <nanobind.nb_func object>¶
- getTensor¶
Return the
idxtensor making up this state representation.
- getTensors¶
Return all the tensors that comprise this state representation.
- get_state_refval¶
Convert the address of the state object to an integer.
- is_on_gpu¶
Return True if this state is on the GPU.
- num_qubits¶
Returns the number of qubits represented by this state.
- overlap¶
Overloaded function.
overlap(self, arg: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State, /) -> complex
Compute the overlap between the provided
State’s.overlap(self, arg: object, /) -> complex
Compute the overlap between the provided
State’s.overlap(self, arg: object, /) -> complex
Compute overlap with general CuPy device array.
- class cudaq.Tensor¶
The
Tensordescribes a pointer to simulation data as well as the rank and extents for that tensorial data it represents.
- class cudaq.QuakeValue(mlirValue, pyKernel, size=None)¶
A
QuakeValuerepresents a handle to an individual function argument of aKernel, or a return value from an operation within it. As documented inmake_kernel(), aQuakeValuecan hold values of the following types: int, float, list/List,qubit, orqvector. TheQuakeValuecan also hold kernel operations such as qubit allocations and measurements.- __add__(other)¶
Return the sum of
self(QuakeValue) andother(float).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = value + 5.0
- __radd__(other)¶
Return the sum of
other(float) andself(QuakeValue).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 + value
- __sub__(other)¶
Return the difference of
self(QuakeValue) andother(float).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = value - 5.0
- __rsub__(other)¶
Return the difference of
other(float) andself(QuakeValue).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 - value
- __neg__()¶
Return the negation of
self(QuakeValue).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = -value
- __mul__(other)¶
Return the product of
self(QuakeValue) withother(float).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = value * 5.0
- __rmul__(other)¶
Return the product of
other(float) withself(QuakeValue).- Raises:
RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 * value
- __getitem__(idx)¶
Return the element of
selfat the providedindex.Note
Only
listorqvectortypeQuakeValue’s may be indexed.- Parameters:
index (int) – The element of
selfthat you’d like to return.- Returns:
A new
QuakeValuefor theindexelement ofself.- Return type:
- Raises:
RuntimeError – if
selfis a non-subscriptableQuakeValue.
- slice(startIdx, count)¶
Return a slice of the given
QuakeValueas a newQuakeValue.Note
The underlying
QuakeValuemust be alistorveq.- Parameters:
- Returns:
A new
QuakeValuecontaining a slice ofselffrom thestartelement to thestart + countelement.- Return type:
- class cudaq.qubit(*args, **kwargs)¶
The qubit is the primary unit of information in a quantum computer. Qubits can be created individually or as part of larger registers.
- class cudaq.qvector(*args, **kwargs)¶
An owning, dynamically sized container for qubits. The semantics of the
qvectorfollows that of astd::vectoror list for qubits.
- class cudaq.ComplexMatrix(*args, **kwargs)¶
The
ComplexMatrixis a thin wrapper around a matrix of complex<double> elements.- __getitem__¶
Return the matrix element at i, j.
- __str__¶
Returns the string representation of the matrix.
- dump¶
Prints the matrix to the standard output.
- minimal_eigenvalue¶
Return the lowest eigenvalue for this
ComplexMatrix.
- num_columns¶
Returns the number of columns in the matrix.
- num_rows¶
Returns the number of rows in the matrix.
- to_numpy¶
Convert
ComplexMatrixto numpy.ndarray.
- class cudaq.SampleResult(*args, **kwargs)¶
A data-type containing the results of a call to
sample(). This includes all measurement counts data from both mid-circuit and terminal measurements.Note
Conditional logic on mid-circuit measurements is no longer supported with
sample. Useruninstead.- __getitem__¶
Return the measurement counts for the given
bitstring.
- __iter__¶
Iterate through the
SampleResultdictionary.
- __len__¶
Return the number of elements in
self. Equivalent to the number of uniquely measured bitstrings.
- clear¶
Clear out all metadata from
self.
- count¶
Return the number of times the given bitstring was observed.
- Parameters:
- Returns:
The number of times the given bitstring was measured during the experiment.
- Return type:
- deserialize¶
Deserialize this SampleResult from an existing vector of integers adhering to the implicit encoding.
- dump¶
Print a string of the raw measurement counts data to the terminal.
- get_marginal_counts¶
Extract the measurement counts data for the provided subset of qubits (
marginal_indices).- Parameters:
- Returns:
A new
SampleResultdictionary containing the extracted measurement data.- Return type:
- get_register_counts¶
Extract the provided sub-register (
register_name) as a newSampleResult.
- get_sequential_data¶
Return the data from the given register (
register_name) as it was collected sequentially. A list of measurement results, not collated into a map.
- get_total_shots¶
Get the total number of shots in the sample result
- items¶
Return the key/value pairs in this
SampleResultdictionary.
- most_probable¶
Return the bitstring that was measured most frequently in the experiment.
- probability¶
Return the probability of measuring the given
bitstring.- Parameters:
- Returns:
The probability of measuring the given
bitstring. Equivalent to the proportion of the total times the bitstring was measured vs. the number of experiments (shots_count).- Return type:
- property register_names¶
(self) -> list[str]
- serialize¶
Serialize this SampleResult to a vector of integer encoding.
- values¶
Return all values (the counts) in this
SampleResultdictionary.
- class cudaq.AsyncSampleResult(impl, mod=None)¶
- class cudaq.ObserveResult(*args, **kwargs)¶
A data-type containing the results of a call to
observe(). This includes any measurement counts data, as well as the global expectation value of the user-definedspin_operator.- counts¶
Overloaded function.
counts(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
Returns a
SampleResultdictionary with the measurement results from the experiment. The result for each individual term of thespin_operatoris stored in its own measurement register. Each register name corresponds to the string representation of the spin term (without any coefficients).counts(self, sub_term: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResultcounts(self, sub_term: object) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
Given a
sub_termof the globalspin_operatorthat was passed toobserve(), return its measurement counts.- Parameters:
sub_term (
SpinOperator) – An individual sub-term of thespin_operator.- Returns:
The measurement counts data for the individual
sub_term.- Return type:
counts(self, sub_term: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
Deprecated - ensure to pass a SpinOperatorTerm instead of a SpinOperator
- dump¶
Dump the raw data from the
SampleResultthat are stored inObserveResultto the terminal.
- expectation¶
Overloaded function.
expectation(self) -> float
Return the expectation value of the
spin_operatorthat was provided inobserve().expectation(self, sub_term: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperatorTerm) -> floatexpectation(self, sub_term: object) -> float
Return the expectation value of an individual
sub_termof the globalspin_operatorthat was passed toobserve().- Parameters:
sub_term (
SpinOperatorTerm) – An individual sub-term of thespin_operator.- Returns:
The expectation value of the
sub_termwith respect to theKernelthat was passed toobserve().- Return type:
expectation(self, sub_term: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) -> float
Deprecated - ensure to pass a SpinOperatorTerm instead of a SpinOperator
- get_spin¶
Return the
SpinOperatorcorresponding to thisObserveResult.
- class cudaq.AsyncObserveResult(*args, **kwargs)¶
A data-type containing the results of a call to
observe_async().The
AsyncObserveResultcontains a future, whoseObserveResultmay be returned via an invocation of thegetmethod.This kicks off a wait on the current thread until the results are available.
See future for more information on this programming pattern.
- get¶
Returns the
ObserveResultfrom the asynchronous observe execution.
- class cudaq.AsyncStateResult¶
A data-type containing the results of a call to
get_state_async(). TheAsyncStateResultmodels a future-like type, whoseStatemay be returned via an invocation of thegetmethod. This kicks off a wait on the current thread until the results are available. See future for more information on this programming pattern.
- class cudaq.EvolveResult(*args, **kwargs)¶
Stores the execution data from an invocation of
evolve().- expectation_values¶
Stores the expectation values, that is the results from the calls to
observe(), at each step in the schedule produced by a call toevolve(), including the final expectation values. Each entry corresponds to one observable provided in theevolve()call. This property is only populated saving intermediate results was requested in the call toevolve(). This value will be None if no intermediate results were requested, or if no observables were specified in the call.
- final_expectation_values¶
Stores the final expectation values, that is the results produced by calls to
observe(), triggered by a call toevolve(). Each entry corresponds to one observable provided in theevolve()call. This value will be None if no observables were specified in the call.
- class cudaq.AsyncEvolveResult¶
Stores the execution data from an invocation of
evolve_async().- get¶
Retrieve the evolution result from the asynchronous evolve execution .
- class cudaq.Resources(*args, **kwargs)¶
A data-type containing the results of a call to
estimate_resources(). This includes all gate counts.- clear¶
Clear out all metadata from
self.
- count¶
Overloaded function.
count(self, arg: str, /) -> int
Get the number of occurrences of a given gate with any number of controls
count(self) -> int
Get the total number of occurrences of all gates
- count_controls¶
Get the number of occurrences of a given gate with the given number of controls
- property depth¶
The circuit depth (longest gate chain on any qubit).
- depth_for_arity¶
Get circuit depth considering only gates of a specific qubit arity. Returns 0 if no gates of that arity exist.
- dump¶
Print a string of the raw resource counts data to the terminal.
- property gate_count_by_arity¶
Gate counts by qubit arity, as a dict mapping arity to count.
- gate_count_for_arity¶
Get gate count for a specific qubit arity (total qubits including controls and targets). Returns 0 if no gates of that arity exist.
- property multi_qubit_depth¶
Max depth across all gate widths >= 2.
- property multi_qubit_gate_count¶
Total count of gates with 2 or more qubits.
- property num_qubits¶
The total number of qubits allocated in the kernel.
- property num_used_qubits¶
The number of qubits touched by at least one quantum operation.
- property per_qubit_depth¶
Per-qubit circuit depth (all gates), as a dict mapping qubit index to depth.
- to_dict¶
Return a dictionary of the raw resource counts that are stored in
self.
Optimizers¶
- cudaq.operators.custom.optimize(dimensions: int, function) tuple[float, list[float]]
Run the optimization procedure.
- Parameters:
dimensions – The number of parameters to optimize
function – The objective function to minimize
- Returns:
tuple of (optimal_value, optimal_parameters)
- cudaq.operators.custom.requires_gradients() bool
Check whether this optimizer requires gradient information.
- Returns:
True if gradients required, False otherwise
- class cudaq.optimizers.GradientDescent(*args, **kwargs)¶
- from_json = <nanobind.nb_func object>¶
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
- class cudaq.optimizers.COBYLA(*args, **kwargs)¶
- from_json = <nanobind.nb_func object>¶
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
- class cudaq.optimizers.NelderMead(*args, **kwargs)¶
- from_json = <nanobind.nb_func object>¶
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
- class cudaq.optimizers.LBFGS(*args, **kwargs)¶
- from_json = <nanobind.nb_func object>¶
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
- class cudaq.optimizers.Adam(*args, **kwargs)¶
- property batch_size¶
Number of samples per batch (default: 1).
For stochastic optimization, determines how many samples are used to compute each gradient estimate. Batch size of 1 corresponds to online learning. Larger batch sizes can provide more stable gradient estimates but require more computation per iteration.
- Type:
- property beta1¶
Exponential decay rate for the first moment estimates (default: 0.9).
Controls the exponential moving average of past gradients (momentum term). Values are typically in the range [0.9, 0.999]. Higher values give more weight to past gradients, providing smoother updates but slower adaptation.
- Type:
- property beta2¶
Exponential decay rate for the second moment estimates (default: 0.999).
Controls the exponential moving average of past squared gradients. Values are typically in the range [0.99, 0.9999]. Higher values provide more stable learning rates but slower adaptation to changing gradient magnitudes.
- Type:
- property epsilon¶
Small constant for numerical stability (default: 1e-8).
Added to the denominator to prevent division by zero when computing adaptive learning rates. Should be a small positive value, typically between 1e-8 and 1e-6.
- Type:
- property f_tol¶
Convergence tolerance on the objective function value (default: 1e-4).
Optimization terminates when the change in objective function value between iterations falls below this threshold. Smaller values lead to tighter convergence but may require more iterations.
- Type:
- from_json = <nanobind.nb_func object>¶
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- property step_size¶
Learning rate (step size) for parameter updates (default: 0.01).
Controls the magnitude of parameter updates at each iteration. Typical values range from 0.001 to 0.1. The effective learning rate is adapted per parameter based on gradient history. Start with 0.001 or 0.01 and adjust based on convergence behavior.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
- class cudaq.optimizers.SGD(*args, **kwargs)¶
- property batch_size¶
Number of samples per batch (default: 1).
For stochastic optimization, determines how many samples are used to compute each gradient estimate. Batch size of 1 corresponds to true stochastic gradient descent. Larger batch sizes (mini-batch SGD) can provide more stable gradient estimates but require more computation per iteration.
- Type:
- property f_tol¶
Convergence tolerance on the objective function value (default: 1e-4).
Optimization terminates when the change in objective function value between iterations falls below this threshold. Smaller values lead to tighter convergence but may require more iterations. Note that with stochastic gradients, convergence may be noisy.
- Type:
- from_json = <nanobind.nb_func object>¶
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- property step_size¶
Learning rate (step size) for parameter updates (default: 0.01).
Controls the magnitude of parameter updates at each iteration. The update rule is: x_new = x_old - step_size * gradient. Typical values range from 0.001 to 0.1. Too large values can cause divergence, while too small values lead to slow convergence.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
- class cudaq.optimizers.SPSA(*args, **kwargs)¶
- from_json = <nanobind.nb_func object>¶
- property gamma¶
Scaling exponent for the step size schedule (default: 0.101).
Controls how the step size decreases over iterations. The step size at iteration k is proportional to (A + k + 1)^(-gamma), where A is a stability constant. Common values are in the range [0.1, 0.6].
- Type:
- property initial_parameters¶
Initial values for the optimization parameters (optional).
Provides a starting point for the optimization. If not specified, the optimizer typically initializes parameters to zeros. Good initial parameter values can significantly improve convergence speed and help avoid poor local minima. The length must match the problem dimension.
Example
optimizer.initial_parameters = [0.5, -0.3, 1.2]
- property lower_bounds¶
Lower bounds for optimization parameters (optional).
Constrains the search space by specifying minimum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.lower_bounds = [-2.0, -2.0] # For 2D problem
- property max_iterations¶
Maximum number of optimizer iterations (default: unlimited).
Sets an upper bound on the number of function evaluations or iterations the optimizer will perform. If not set, the optimizer may run until convergence or until another stopping criterion is met.
- Type:
- property step_size¶
Evaluation step size for gradient approximation (default: 0.3).
Controls the magnitude of perturbations used to approximate gradients. Larger values provide coarser gradient estimates but may be more robust to noise. Typical values range from 0.1 to 0.5.
- Type:
- to_json¶
Convert optimizer to JSON string
- property upper_bounds¶
Upper bounds for optimization parameters (optional).
Constrains the search space by specifying maximum allowed values for each parameter. When specified, the length must match the problem dimension.
Example
optimizer.upper_bounds = [2.0, 2.0] # For 2D problem
Gradients¶
- class cudaq.gradients.gradient¶
- class cudaq.gradients.CentralDifference(*args, **kwargs)¶
- compute¶
Compute the gradient of the provided
parameter_vectorwith respect to its loss function, using theCentralDifferencemethod.
- from_json = <nanobind.nb_func object>¶
- to_json¶
Convert gradient to JSON string
Noisy Simulation¶
- class cudaq.NoiseModel(*args, **kwargs)¶
The
NoiseModeldefines a set ofKrausChannel’s applied to specific qubits after the invocation of specified quantum operations.- __init__¶
Construct a noise model with all built-in channels pre-registered.
- add_all_qubit_channel¶
Add the given
KrausChannelto be applied after invocation of the specified quantum operation on arbitrary qubits.- Parameters:
operator (str) – The quantum operator to apply the noise channel to.
channel (cudaq.KrausChannel) – The
KrausChannelto apply to the specifiedoperatoron any arbitrary qubits.num_controls – Number of control bits. Default is 0 (no control bits).
- add_channel¶
Overloaded function.
add_channel(self, operator: str, qubits: collections.abc.Sequence[int], channel: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.KrausChannel) -> None
Add the given
KrausChannelto be applied after invocation of the specified quantum operation.- Parameters:
operator (str) – The quantum operator to apply the noise channel to.
qubits (List[int]) – The qubit/s to apply the noise channel to.
channel (cudaq.KrausChannel) – The
KrausChannelto apply to the specifiedoperatoron the specifiedqubits.
add_channel(self, operator: str, pre: collections.abc.Callable[[collections.abc.Sequence[int], collections.abc.Sequence[float]], cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.KrausChannel]) -> None
Add the given
KrausChannelgenerator callback to be applied after invocation of the specified quantum operation.- Parameters:
operator (str) – The quantum operator to apply the noise channel to.
pre (Callable) – The callback which takes qubits operands and gate parameters and returns a concrete
KrausChannelto apply to the specifiedoperator.
- get_channels¶
Return the
KrausChannel’s that make up this noise model.
- class cudaq.BitFlipChannel(*args, **kwargs)¶
Models the decoherence of the qubit state. Its constructor expects a float value,
probability, representing the probability that the qubit flips from the 1-state to the 0-state, or vice versa. E.g, the probability of a random X-180 rotation being applied to the qubit.The Kraus Channels are thereby defined to be:
K_0 = sqrt(1 - probability) * I
K_1 = sqrt(probability ) * X
The probability of the qubit remaining in the same state is therefore
1 - probability.- __init__¶
Overloaded function.
__init__(self, arg: collections.abc.Sequence[float], /) -> None__init__(self, probability: float) -> None
Initialize the
BitFlipChannelwith the providedprobability.
- class cudaq.PhaseFlipChannel(*args, **kwargs)¶
Models the decoherence of the qubit phase. Its constructor expects a float value,
probability, representing the probability of a random Z-180 rotation being applied to the qubit.The Kraus Channels are thereby defined to be:
K_0 = sqrt(1 - probability) * I
K_1 = sqrt(probability ) * Z
The probability of the qubit phase remaining untouched is therefore
1 - probability.- __init__¶
Overloaded function.
__init__(self, arg: collections.abc.Sequence[float], /) -> None__init__(self, probability: float) -> None
Initialize the
PhaseFlipChannelwith the providedprobability.
- class cudaq.DepolarizationChannel(*args, **kwargs)¶
Models the decoherence of the qubit state and phase into a mixture ” of the computational basis states,
|0>and|1>.The Kraus Channels are thereby defined to be:
K_0 = sqrt(1 - probability) * I
K_1 = sqrt(probability / 3) * X
K_2 = sqrt(probability / 3) * Y
K_3 = sqrt(probability / 3) * Z
where I, X, Y, Z are the 2x2 Pauli matrices.
The constructor expects a float value,
probability, representing the probability the state decay will occur. The qubit will remain untouched, therefore, with a probability of1 - probability. And the X,Y,Z operators will be applied with a probability ofprobability / 3.For
probability = 0.0, the channel will behave noise-free. Forprobability = 0.75, the channel will fully depolarize the state. Forprobability = 1.0, the channel will be uniform.- __init__¶
Overloaded function.
__init__(self, arg: collections.abc.Sequence[float], /) -> None__init__(self, probability: float) -> None
Initialize the
DepolarizationChannelwith the providedprobability.
- class cudaq.AmplitudeDampingChannel(*args, **kwargs)¶
Models the dissipation of energy due to system interactions with the environment.
The Kraus Channels are thereby defined to be:
K_0 = sqrt(1 - probability) * I
K_1 = sqrt(probability) * 0.5 * (X + iY)
Its constructor expects a float value,
probability, representing the probability that the qubit will decay to its ground state. The probability of the qubit remaining in the same state is therefore1 - probability.- __init__¶
Overloaded function.
__init__(self, arg: collections.abc.Sequence[float], /) -> None__init__(self, probability: float) -> None
Initialize the
AmplitudeDampingChannelwith the providedprobability.
- class cudaq.PhaseDamping(*args, **kwargs)¶
A Kraus channel that models the single-qubit phase damping error. This is similar to AmplitudeDamping, but for phase.
- class cudaq.XError(*args, **kwargs)¶
A Pauli error that applies the X operator when an error occurs. It is the same as BitFlipChannel.
- class cudaq.YError(*args, **kwargs)¶
A Pauli error that applies the Y operator when an error occurs.
- class cudaq.ZError(*args, **kwargs)¶
A Pauli error that applies the Z operator when an error occurs. It is the same as PhaseFlipChannel.
- class cudaq.Pauli1(*args, **kwargs)¶
A single-qubit Pauli error that applies either an X error, Y error, or Z error. The probability of each X, Y, or Z error is supplied as a parameter.
- class cudaq.Pauli2(*args, **kwargs)¶
A 2-qubit Pauli error that applies one of the following errors, with the probabilities specified as a vector. Possible errors: IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, and ZZ.
- class cudaq.Depolarization1(*args, **kwargs)¶
The same as DepolarizationChannel (single qubit depolarization)
- class cudaq.Depolarization2(*args, **kwargs)¶
A 2-qubit depolarization error that applies one of the following errors. Possible errors: IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, and ZZ.
- class cudaq.KrausChannel(*args, **kwargs)¶
The
KrausChannelis composed of a list ofKrausOperator’s and is applied to a specific qubit or set of qubits.- __getitem__¶
Return the
KrausOperatorat the given index in thisKrausChannel.
- append¶
Add a
KrausOperatorto thisKrausChannel.
- get_ops¶
Return the
KrausOperator’s in thisKrausChannel.
- property noise_type¶
(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.NoiseModelType
- property parameters¶
(self) -> list[float]
- class cudaq.KrausOperator(*args, **kwargs)¶
The
KrausOperatoris represented by a matrix and serves as an element of a quantum channel such thatSum Ki Ki^dag = I.- property col_count¶
The number of columns in the matrix representation of this
KrausOperator.
- property row_count¶
The number of rows in the matrix representation of this
KrausOperator.
MPI Submodule¶
- cudaq.mpi.all_gather(arg0: int, arg1: collections.abc.Sequence[float], /) list[float]¶
- cudaq.mpi.all_gather(arg0: int, arg1: collections.abc.Sequence[int], /) list[int]
Overloaded function.
all_gather(arg0: int, arg1: collections.abc.Sequence[float], /) -> list[float]
Gather and scatter the
locallist of floating-point numbers, returning a concatenation of all lists across all ranks. The total global list size must be provided.all_gather(arg0: int, arg1: collections.abc.Sequence[int], /) -> list[int]
Gather and scatter the
locallist of integers, returning a concatenation of all lists across all ranks. The total global list size must be provided.
ORCA Submodule¶
- cudaq.orca.sample(input_state: collections.abc.Sequence[int], loop_lengths: collections.abc.Sequence[int], bs_angles: collections.abc.Sequence[float], ps_angles: collections.abc.Sequence[float], n_samples: int = 10000, qpu_id: int = 0) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult¶
- cudaq.orca.sample(input_state: collections.abc.Sequence[int], loop_lengths: collections.abc.Sequence[int], bs_angles: collections.abc.Sequence[float], n_samples: int = 10000, qpu_id: int = 0) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
Performs Time Bin Interferometer (TBI) boson sampling experiments on ORCA’s backends
PTSBE Submodule¶
The cudaq.ptsbe submodule implements Pre-Trajectory Sampling with Batch
Execution (PTSBE). For a conceptual overview and usage tutorial see
Pre-Trajectory Sampling with Batch Execution (PTSBE).
Sampling Functions¶
- cudaq.ptsbe.sample(kernel, *args, shots_count=1000, noise_model=None, max_trajectories=None, sampling_strategy=None, shot_allocation=None, return_execution_data=False, include_sequential_data=False)¶
Sample using Pre-Trajectory Sampling with Batch Execution (
PTSBE).Pre-samples noise realizations (trajectories) and batches circuit executions by unique noise configuration, enabling efficient noisy sampling of many shots.
When called with list arguments (broadcast mode), executes the kernel for each set of arguments and returns a list of results.
- Parameters:
kernel – The quantum kernel to execute.
shots_count (int) – Number of measurement shots. Defaults to 1000.
noise_model – Optional noise model for gate-based noise. Noise can also be specified inside the kernel via
cudaq.apply_noise(); both can be used together.max_trajectories (int or
None) – Maximum unique trajectories to generate.Nonemeans use the number of shots. Note for large shot counts setting a maximum is recommended to get the benefits of PTS.sampling_strategy (
PTSSamplingStrategyorNone) – Strategy for trajectory generation.Noneuses the default probabilistic sampling strategy.shot_allocation (
ShotAllocationStrategyorNone) – Strategy for allocating shots across trajectories.Noneuses the default proportional (weight-based) allocation.return_execution_data (bool) – Include circuit structure, trajectory specifications, and per-trajectory measurement outcomes in the returned result. Defaults to
False.include_sequential_data (bool) – Populate per-shot sequential bitstring data on the result. Defaults to
False.
- Returns:
- Measurement results. Returns a list of results
in broadcast mode.
- Return type:
SampleResult- Raises:
RuntimeError – If the kernel is invalid or arguments are invalid.
- cudaq.ptsbe.sample_async(kernel, *args, shots_count=1000, noise_model=None, max_trajectories=None, sampling_strategy=None, shot_allocation=None, return_execution_data=False, include_sequential_data=False)¶
Asynchronously sample using PTSBE. Returns a future whose result can be retrieved via
.get().- Parameters:
kernel – The quantum kernel to execute.
shots_count (int) – Number of measurement shots. Defaults to 1000.
noise_model – Optional noise model for gate-based noise; noise can also be specified in the kernel via
cudaq.apply_noise().max_trajectories (int or
None) – Maximum unique trajectories.sampling_strategy (
PTSSamplingStrategyorNone) – Strategy for trajectory generation.shot_allocation (
ShotAllocationStrategyorNone) – Strategy for allocating shots across trajectories.return_execution_data (bool) – Include execution data in the result.
include_sequential_data (bool) – Populate per-shot sequential data.
- Returns:
- A future whose
.get()returns the SampleResult.
- A future whose
- Return type:
AsyncPTSBESampleResult- Raises:
RuntimeError – If the kernel is invalid or arguments are invalid.
Result Type¶
Trajectory Sampling Strategies¶
- class cudaq.ptsbe.PTSSamplingStrategy¶
Base class for trajectory sampling strategies.
- name¶
Get the name of this strategy.
- class cudaq.ptsbe.ProbabilisticSamplingStrategy(*args, **kwargs)¶
Sample trajectories randomly based on their occurrence probabilities.
- class cudaq.ptsbe.OrderedSamplingStrategy(*args, **kwargs)¶
Sample trajectories sorted by probability in descending order.
- class cudaq.ptsbe.ExhaustiveSamplingStrategy(*args, **kwargs)¶
Enumerate all possible trajectories in lexicographic order.
Shot Allocation Strategy¶
Execution Data¶
- class cudaq.ptsbe.PTSBEExecutionData¶
Container for PTSBE execution data including circuit structure, trajectory specifications, and per-trajectory measurement outcomes.
- count_instructions¶
Count instructions of a given type.
- get_trajectory¶
Look up a trajectory by its ID. Returns None if not found.
- property instructions¶
(self) -> list[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ptsbe.TraceInstruction]
- property trajectories¶
(self) -> list[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ptsbe.KrausTrajectory]
- class cudaq.ptsbe.TraceInstruction¶
Single operation in the execution trace.
- property channel¶
(self) -> object
- property controls¶
(self) -> list[int]
- property name¶
(self) -> str
- property params¶
(self) -> list[float]
- property targets¶
(self) -> list[int]
- property type¶
(self) -> cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ptsbe.TraceInstructionType
- class cudaq.ptsbe.TraceInstructionType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
Type discriminator for trace instructions.
Trajectory and Selection Types¶
- class cudaq.ptsbe.KrausTrajectory¶
Complete specification of one noise trajectory with outcomes.
- property kraus_selections¶
(self) -> list[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ptsbe.KrausSelection]
- property measurement_counts¶
(self) -> dict[str, int]
- property multiplicity¶
Number of times this trajectory was sampled.
- property num_shots¶
(self) -> int
- property probability¶
(self) -> float
- property trajectory_id¶
(self) -> int
- property weight¶
Allocation weight for shot distribution.