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
QuakeValue
for 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
Kernel
provides an API for dynamically constructing quantum circuits. TheKernel
programmatically represents the circuit as an MLIR function using the Quake dialect.- arguments¶
The arguments accepted by the
Kernel
function. Read-only.- Type:
List[
QuakeValue
]
- class cudaq.PyKernelDecorator(function, verbose=False, module=None, kernelName=None, funcSrc=None, signature=None, location=None, overrideGlobalScopedVars=None)¶
The
PyKernelDecorator
serves as a standard Python decorator that takes the decorated function as input and optionally lowers its AST representation to executable code via MLIR. This decorator enables full JIT compilation mode, where the function is lowered to an MLIR representation.This decorator exposes a call overload that executes the code via the MLIR
ExecutionEngine
for the MLIR mode.- __call__(*args)¶
Invoke the CUDA-Q kernel. JIT compilation of the kernel AST to MLIR will occur here if it has not already occurred, except when the target requires custom handling.
- __str__()¶
Return the MLIR Module string representation for this kernel.
- compile()¶
Compile the Python function AST to MLIR. This is a no-op if the kernel is already compiled.
- extract_c_function_pointer(name=None)¶
Return the C function pointer for the function with given name, or with the name of this kernel if not provided.
- static from_json(jStr, overrideDict=None)¶
Convert a JSON string into a new PyKernelDecorator object.
- merge_kernel(otherMod)¶
Merge the kernel in this PyKernelDecorator (the ModuleOp) with the provided ModuleOp.
- synthesize_callable_arguments(funcNames)¶
Given this Kernel has callable block arguments, synthesize away these callable arguments with the in-module FuncOps with given names. The name at index 0 in the list corresponds to the first callable block argument, index 1 to the second callable block argument, etc.
- to_json()¶
Convert
self
to a JSON-serialized version of the kernel such thatfrom_json
can 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.kernel
represents 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
kernel
at the given kernelarguments
over the specified number of circuit executions (shots_count
). Each argument inarguments
provided can be a list orndarray
of arguments of the specified kernel argument type, and in this case, thesample
functionality will be broadcasted over all argument sets and a list ofsample_result
instances will be returned.- Parameters:
kernel (
Kernel
) – TheKernel
to executeshots_count
times 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
float
values as input, thesample
call should be structured ascudaq.sample(kernel, firstFloat, secondFloat)
. For broadcasting of thesample
function, the arguments should be structured as alist
orndarray
of 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 optionalNoiseModel
to 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 ofsample
function broadcasting.- Return type:
SampleResult
orlist[SampleResult]
- cudaq.sample_async()¶
- cudaq.sample_async(kernel: object, \*args, shots_count: int = 1000, explicit_measurements: bool = False, qpu_id: int = 0) AsyncSampleResult
Asynchronously sample the state of the provided
kernel
at the specified number of circuit executions (shots_count
). When targeting a quantum platform with more than one QPU, the optionalqpu_id
allows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get()
.- Parameters:
kernel (
Kernel
) – TheKernel
to executeshots_count
times 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.
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.observe(kernel, spin_operator, *args, shots_count=0, noise_model=None, num_trajectories=None, execution=None)¶
Compute the expected value of the
spin_operator
with respect to thekernel
. If the inputspin_operator
is a list ofSpinOperator
then 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 inarguments
provided can be a list orndarray
of arguments of the specified kernel argument type, and in this case, theobserve
functionality will be broadcasted over all argument sets and a list ofobserve_result
instances will be returned. If both the inputspin_operator
andarguments
are broadcast lists, a nested list of results overarguments
thenspin_operator
will be returned.- Parameters:
kernel (
Kernel
) – TheKernel
to evaluate the expectation value with respect to.spin_operator (
SpinOperator
orlist[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 optionalNoiseModel
to 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. Key-word only.
- Returns:
A data-type containing the expectation value of the
spin_operator
with respect to thekernel(*arguments)
, or a list of such results in the case ofobserve
function broadcasting. Ifshots_count
was provided, theObserveResult
will also contain aSampleResult
dictionary.- Return type:
- cudaq.observe_async()¶
- cudaq.observe_async(kernel: object, spin_operator: object, \*args, qpu_id: int = 0, shots_count: int = -1) AsyncObserveResult
Compute the expected value of the
spin_operator
with respect to thekernel
asynchronously. 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_id
allows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get()
.- Parameters:
kernel (
Kernel
) – TheKernel
to 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()¶
- cudaq.get_state(arg0: object, \*args) State
Return the
State
of the system after execution of the providedkernel
.- Parameters:
# Example: import numpy as np # Define a kernel that will produced the all |11...1> state. kernel = cudaq.make_kernel() 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()¶
- cudaq.get_state_async(kernel: object, \*args, qpu_id: int = 0) AsyncStateResult
Asynchronously retrieve the state generated by the given quantum kernel. When targeting a quantum platform with more than one QPU, the optional
qpu_id
allows 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 (state vector or density matrix) data).
- Return type:
- cudaq.vqe(*args, **kwargs)¶
Overloaded function.
- cudaq.vqe(kernel: object, gradient_strategy: gradients.gradient, spin_operator: object, optimizer: optimizers.optimizer, parameter_count: int, shots: int = -1) tuple[float, list[float]]
- cudaq.vqe(kernel: object, gradient_strategy: gradients.gradient, spin_operator: object, optimizer: optimizers.optimizer, parameter_count: int, argument_mapper: Callable, shots: int = -1) tuple[float, list[float]]
- cudaq.draw(*args, **kwargs)¶
Overloaded function.
- cudaq.draw(arg0: str, arg1: object, \*args) str
Return a string representing the drawing of the execution path, in the format specified as the first argument. If the format is ‘ascii’, the output will be a UTF-8 encoded string. If the format is ‘latex’, the output will be a LaTeX string.
- Parameters:
- cudaq.draw(arg0: object, \*args) str
Return a UTF-8 encoded string representing drawing of the execution path, i.e., the trace, of the provided
kernel
.- Parameters:
- Returns:
The UTF-8 encoded 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.draw(bell_pair)) # Output # ╭───╮ # q0 : ┤ h ├──●── # ╰───╯╭─┴─╮ # q1 : ─────┤ x ├ # ╰───╯ # Example with arguments import cudaq @cudaq.kernel def kernel(angle:float): q = cudaq.qubit() h(q) ry(angle, q) print(cudaq.draw(kernel, 0.59)) # Output # ╭───╮╭──────────╮ # q0 : ┤ h ├┤ ry(0.59) ├ # ╰───╯╰──────────╯
- cudaq.translate()¶
- cudaq.translate(kernel: object, \*args, format: str = 'qir') str
Return a UTF-8 encoded string representing drawing of the execution path, i.e., the trace, of the provided
kernel
.- Parameters:
format (str) – format to translate to. Available formats:
qir
,qir-base
,qir-adaptive
,openqasm2
.*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-8 encoded 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 }
Backend Configuration¶
- cudaq.has_target()¶
-
Return true if the
cudaq.Target
with the given name exists.
- cudaq.get_target(*args, **kwargs)¶
Overloaded function.
Return the
cudaq.Target
with the given name. Will raise an exception if the name is not valid.- cudaq.get_target() Target
Return the
cudaq.Target
with the given name. Will raise an exception if the name is not valid.
- cudaq.get_targets()¶
-
Return all available
cudaq.Target
instances on the current system.
- cudaq.set_target(*args, **kwargs)¶
Overloaded function.
- cudaq.set_target(arg0: Target, \*\*kwargs) None
Set the
cudaq.Target
to be used for CUDA-Q kernel execution. Can provide optional, target-specific configuration data via Python kwargs.- cudaq.set_target(arg0: str, \*\*kwargs) None
Set the
cudaq.Target
with given name to be used for CUDA-Q kernel execution. Can provide optional, target-specific configuration data via Python kwargs.
- cudaq.set_noise()¶
- cudaq.set_noise(arg0: cudaq.NoiseModel) None
Set the underlying noise model.
- cudaq.unset_noise()¶
- cudaq.unset_noise() None
Clear backend simulation from any existing noise models.
- 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.KrausChannel
that 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.KrausChannel
being used. The arguments are a concatenated list of parameters and targets. For example, to apply a 2-qubit depolarization channel, which hasnum_parameters = 1
andnum_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
- cudaq.initialize_cudaq()¶
- cudaq.initialize_cudaq(\*\*kwargs) None
Initialize the CUDA-Q environment.
Dynamics¶
- cudaq.evolve(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: Optional[Schedule] = None, initial_state: Optional[Union[State, InitialState, Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State | cudaq.dynamics.helpers.InitialState]]] = 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=False, integrator: Optional[BaseIntegrator] = None, shots_count: 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 theparameter
property 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_results
is set to True, 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
EvolveResult
for 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: Optional[Schedule] = None, initial_state: Optional[Union[State, InitialState, Sequence[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State | cudaq.dynamics.helpers.InitialState]]] = 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=False, 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.evolve
for 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
EvolveResult
for 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.
- class cudaq.dynamics.helpers.InitialState(value)¶
Enum to specify the initial quantum state.
- cudaq.dynamics.cudm_state.to_cupy_array(state)¶
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(generator: Union[complexfloating, complex, float, int, Callable[[...], numpy.complexfloating | complex | float | int]], parameter_info: Optional[Mapping[str, str]] = None)¶
- classmethod const(constant_value: numpy.complexfloating | complex | float | int) ScalarOperator ¶
Creates a scalar operator that has a constant value.
- is_constant()¶
- is_constant(self: ScalarOperator) bool
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
parameter
property.
- 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
evolve
API 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
- 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
create
function 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
create
function must take an argument calleddimension
(ordim
for short), if the operator acts on a single degree of freedom, and an argument calleddimensions
(ordims
for 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¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: SpinOperator) SpinOperator
Removes all identity operators from the operator.
- canonicalize(self: SpinOperator, arg0: set[int]) 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()¶
- copy(self: SpinOperator) SpinOperator
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()¶
- distribute_terms(self: SpinOperator, arg0: int) list[SpinOperator]
Partitions the terms of the sums into the given number of separate sums.
- dump()¶
- dump(self: SpinOperator) None
Prints the string representation of the operator to the standard output.
- static empty()¶
- empty() SpinOperator
Creates a sum operator with no terms. And empty sum is the neutral element for addition; multiplying an empty sum with anything will still result in an empty sum.
- static empty_op()¶
- empty_op() SpinOperator
Deprecated - use
empty
instead.
- for_each_pauli()¶
- for_each_pauli(self: SpinOperator, function: Callable) None
Deprecated - iterator over sum and then iterator over term instead.
- for_each_term()¶
- for_each_term(self: SpinOperator, function: Callable) None
Deprecated - use standard iteration instead.
- static from_json()¶
- from_json(arg0: str) SpinOperator
Convert JSON string (‘[d1, d2, d3, …]’) to spin_op
- static from_word()¶
- from_word(arg0: str) SpinOperatorTerm
Creates an operator from a Pauli word string.
- get_coefficient()¶
- get_coefficient(self: SpinOperator) complex
Deprecated - use
evaluate_coefficient
on each term (product operator) instead.
- get_qubit_count()¶
- get_qubit_count(self: SpinOperator) int
Deprecated - use
qubit_count
instead.
- get_term_count()¶
- get_term_count(self: SpinOperator) int
Deprecated - use
term_count
instead.
- static identity(*args, **kwargs)¶
Overloaded function.
- identity() SpinOperatorTerm
Creates a product operator with constant value 1. The identity operator is the neutral element for multiplication.
- identity(arg0: int) SpinOperatorTerm
Creates a product operator that applies the identity to the given target index.
- is_identity()¶
- is_identity(self: SpinOperator) bool
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.
- static random()¶
- random(qubit_count: int, term_count: int, seed: int = 2052931986) SpinOperator
Return a random spin operator with the given number of terms (
term_count
) where each term acts on all targets in the open range [0, qubit_count). An optional seed value may also be provided.
- serialize()¶
- serialize(self: SpinOperator) list[float]
Returns the serialized data representation of the operator.
- property term_count¶
Returns the number of terms in the operator.
- to_json()¶
- to_json(self: SpinOperator) object
Convert spin_op to JSON string: ‘[d1, d2, d3, …]’
- to_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: SpinOperator, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_sparse_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_string()¶
- to_string(self: SpinOperator, print_coefficient: bool = True) str
Deprecated - use the standard
str
conversion orget_pauli_word
on each term instead.
- trim(*args, **kwargs)¶
Overloaded function.
- trim(self: SpinOperator, tol: float = 0.0, parameters: dict[str, complex] = {}) SpinOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- trim(self: SpinOperator, tol: float = 0.0, \*\*kwargs) SpinOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.spin.SpinOperatorTerm¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: SpinOperatorTerm) SpinOperatorTerm
Removes all identity operators from the operator.
- canonicalize(self: SpinOperatorTerm, arg0: set[int]) 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
evaluate
method.
- copy()¶
- copy(self: SpinOperatorTerm) SpinOperatorTerm
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()¶
- distribute_terms(self: SpinOperatorTerm, chunk_count: int) list[SpinOperator]
Deprecated - instantiate a
SpinOperator
from thisSpinOperatorTerm
and call distribute_terms on that.
- dump()¶
- dump(self: SpinOperatorTerm) None
Prints the string representation of the operator to the standard output.
- evaluate_coefficient()¶
- evaluate_coefficient(self: SpinOperatorTerm, parameters: dict[str, complex] = {}) complex
Returns the evaluated coefficient of the product operator.
- for_each_pauli()¶
- for_each_pauli(self: SpinOperatorTerm, function: Callable) None
Deprecated - use standard iteration instead.
- static from_json()¶
- from_json(arg0: str) SpinOperatorTerm
Convert JSON string (‘[d1, d2, d3, …]’) to spin_op
- get_binary_symplectic_form()¶
- get_binary_symplectic_form(self: SpinOperatorTerm) list[bool]
Gets the binary symplectic representation of this operator.
- get_coefficient()¶
- get_coefficient(self: SpinOperatorTerm) complex
Deprecated - use
evaluate_coefficient
instead.
- get_pauli_word()¶
- get_pauli_word(self: SpinOperatorTerm, pad_identities: int = 0) str
Gets the Pauli word representation of this product operator.
- get_qubit_count()¶
- get_qubit_count(self: SpinOperatorTerm) int
Deprecated - use
qubit_count
instead.
- get_raw_data()¶
-
Deprecated.
- is_identity()¶
- is_identity(self: SpinOperatorTerm) bool
Checks if all operators in the product are the identity. Note: 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()¶
- serialize(self: SpinOperatorTerm) list[float]
Returns the serialized data representation of the operator.
- 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()¶
- to_json(self: SpinOperatorTerm) object
Convert spin_op to JSON string: ‘[d1, d2, d3, …]’
- to_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: SpinOperatorTerm, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_sparse_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_string()¶
- to_string(self: SpinOperatorTerm, print_coefficient: bool = True) str
Deprecated - use the standard
str
conversion or useget_pauli_word
instead.
- class cudaq.operators.spin.SpinOperatorElement¶
- as_pauli()¶
- as_pauli(self: SpinOperatorElement) 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(*args, **kwargs)¶
Overloaded function.
Returns the matrix representation of the operator.
- to_matrix(self: SpinOperatorElement, dimensions: dict[int, int] = {}, \*\*kwargs) numpy.ndarray[]
Returns the matrix representation of the operator.
- to_string()¶
- to_string(self: SpinOperatorElement, include_degrees: bool) str
Returns the string representation of the operator.
- class cudaq.spin.Pauli¶
An enumeration representing the types of Pauli matrices.
Members:
X
Y
Z
I
- property name¶
object) -> str :noindex:
- Type:
- name(self
- cudaq.spin.canonicalized(*args, **kwargs)¶
Overloaded function.
- cudaq.spin.canonicalized(arg0: SpinOperatorTerm) SpinOperatorTerm
Removes all identity operators from the operator.
- cudaq.spin.canonicalized(arg0: SpinOperatorTerm, arg1: set[int]) 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.
- cudaq.spin.canonicalized(arg0: SpinOperator) SpinOperator
Removes all identity operators from the operator.
- cudaq.spin.canonicalized(arg0: SpinOperator, arg1: set[int]) 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.
- cudaq.spin.empty()¶
- cudaq.spin.empty() SpinOperator
Returns sum operator with no terms. Note that a sum with no terms multiplied by anything still is a sum with no terms.
- cudaq.spin.i()¶
- cudaq.spin.i(target: int) SpinOperatorTerm
Returns a Pauli I spin operator on the given target qubit index.
- cudaq.spin.identities()¶
- cudaq.spin.identities(first: int, last: int) SpinOperatorTerm
Creates a product operator that applies an identity operation to all degrees of freedom in the open range [first, last).
- cudaq.spin.identity(*args, **kwargs)¶
Overloaded function.
- cudaq.spin.identity() SpinOperatorTerm
Returns product operator with constant value 1.
- cudaq.spin.identity(target: int) SpinOperatorTerm
Returns an identity operator on the given target index.
- cudaq.spin.minus()¶
- cudaq.spin.minus(target: int) SpinOperator
Return a sigma minus spin operator on the given target qubit index.
- cudaq.spin.plus()¶
- cudaq.spin.plus(target: int) SpinOperator
Return a sigma plus spin operator on the given target qubit index.
- cudaq.spin.x()¶
- cudaq.spin.x(target: int) SpinOperatorTerm
Returns a Pauli X spin operator on the given target qubit index.
- cudaq.spin.y()¶
- cudaq.spin.y(target: int) SpinOperatorTerm
Returns a Pauli Y spin operator on the given target qubit index.
- cudaq.spin.z()¶
- cudaq.spin.z(target: int) SpinOperatorTerm
Returns a Pauli Z spin operator on the given target qubit index.
Fermion Operators¶
- class cudaq.operators.fermion.FermionOperator¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: FermionOperator) FermionOperator
Removes all identity operators from the operator.
- canonicalize(self: FermionOperator, arg0: set[int]) 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()¶
- copy(self: FermionOperator) FermionOperator
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()¶
- distribute_terms(self: FermionOperator, arg0: int) list[FermionOperator]
Partitions the terms of the sums into the given number of separate sums.
- dump()¶
- dump(self: FermionOperator) None
Prints the string representation of the operator to the standard output.
- static empty()¶
- empty() FermionOperator
Creates a sum operator with no terms. And empty sum is the neutral element for addition; multiplying an empty sum with anything will still result in an empty sum.
- static identity(*args, **kwargs)¶
Overloaded function.
- identity() FermionOperatorTerm
Creates a product operator with constant value 1. The identity operator is the neutral element for multiplication.
- identity(arg0: int) FermionOperatorTerm
Creates a product operator that applies the identity to the given target index.
- 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(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: FermionOperator, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_sparse_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- trim(*args, **kwargs)¶
Overloaded function.
- trim(self: FermionOperator, tol: float = 0.0, parameters: dict[str, complex] = {}) FermionOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- trim(self: FermionOperator, tol: float = 0.0, \*\*kwargs) FermionOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.fermion.FermionOperatorTerm¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: FermionOperatorTerm) FermionOperatorTerm
Removes all identity operators from the operator.
- canonicalize(self: FermionOperatorTerm, arg0: set[int]) 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
evaluate
method.
- copy()¶
- copy(self: FermionOperatorTerm) FermionOperatorTerm
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()¶
- dump(self: FermionOperatorTerm) None
Prints the string representation of the operator to the standard output.
- evaluate_coefficient()¶
- evaluate_coefficient(self: FermionOperatorTerm, parameters: dict[str, complex] = {}) complex
Returns the evaluated coefficient of the product operator.
- is_identity()¶
- is_identity(self: FermionOperatorTerm) bool
Checks if all operators in the product are the identity. Note: 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(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: FermionOperatorTerm, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_sparse_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- class cudaq.operators.fermion.FermionOperatorElement¶
- 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(*args, **kwargs)¶
Overloaded function.
Returns the matrix representation of the operator.
- to_matrix(self: FermionOperatorElement, dimensions: dict[int, int] = {}, \*\*kwargs) numpy.ndarray[]
Returns the matrix representation of the operator.
- to_string()¶
- to_string(self: FermionOperatorElement, include_degrees: bool) str
Returns the string representation of the operator.
- cudaq.fermion.annihilate()¶
- cudaq.fermion.annihilate(target: int) FermionOperatorTerm
Returns a fermionic annihilation operator on the given target index.
- cudaq.fermion.canonicalized(*args, **kwargs)¶
Overloaded function.
- cudaq.fermion.canonicalized(arg0: FermionOperatorTerm) FermionOperatorTerm
Removes all identity operators from the operator.
- cudaq.fermion.canonicalized(arg0: FermionOperatorTerm, arg1: set[int]) 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.
- cudaq.fermion.canonicalized(arg0: FermionOperator) FermionOperator
Removes all identity operators from the operator.
- cudaq.fermion.canonicalized(arg0: FermionOperator, arg1: set[int]) 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.
- cudaq.fermion.create()¶
- cudaq.fermion.create(target: int) FermionOperatorTerm
Returns a fermionic creation operator on the given target index.
- cudaq.fermion.empty()¶
- cudaq.fermion.empty() FermionOperator
Returns sum operator with no terms. Note that a sum with no terms multiplied by anything still is a sum with no terms.
- cudaq.fermion.identities()¶
- cudaq.fermion.identities(first: int, last: int) FermionOperatorTerm
Creates a product operator that applies an identity operation to all degrees of freedom in the open range [first, last).
- cudaq.fermion.identity(*args, **kwargs)¶
Overloaded function.
- cudaq.fermion.identity() FermionOperatorTerm
Returns product operator with constant value 1.
- cudaq.fermion.identity(target: int) FermionOperatorTerm
Returns an identity operator on the given target index.
- cudaq.fermion.number()¶
- cudaq.fermion.number(target: int) FermionOperatorTerm
Returns a fermionic number operator on the given target index.
Boson Operators¶
- class cudaq.operators.boson.BosonOperator¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: BosonOperator) BosonOperator
Removes all identity operators from the operator.
- canonicalize(self: BosonOperator, arg0: set[int]) 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()¶
- copy(self: BosonOperator) BosonOperator
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()¶
- distribute_terms(self: BosonOperator, arg0: int) list[BosonOperator]
Partitions the terms of the sums into the given number of separate sums.
- dump()¶
- dump(self: BosonOperator) None
Prints the string representation of the operator to the standard output.
- static empty()¶
- empty() BosonOperator
Creates a sum operator with no terms. And empty sum is the neutral element for addition; multiplying an empty sum with anything will still result in an empty sum.
- static identity(*args, **kwargs)¶
Overloaded function.
- identity() BosonOperatorTerm
Creates a product operator with constant value 1. The identity operator is the neutral element for multiplication.
- identity(arg0: int) BosonOperatorTerm
Creates a product operator that applies the identity to the given target index.
- 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(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: BosonOperator, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_sparse_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- trim(*args, **kwargs)¶
Overloaded function.
- trim(self: BosonOperator, tol: float = 0.0, parameters: dict[str, complex] = {}) BosonOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- trim(self: BosonOperator, tol: float = 0.0, \*\*kwargs) BosonOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.boson.BosonOperatorTerm¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: BosonOperatorTerm) BosonOperatorTerm
Removes all identity operators from the operator.
- canonicalize(self: BosonOperatorTerm, arg0: set[int]) 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
evaluate
method.
- copy()¶
- copy(self: BosonOperatorTerm) BosonOperatorTerm
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()¶
- dump(self: BosonOperatorTerm) None
Prints the string representation of the operator to the standard output.
- evaluate_coefficient()¶
- evaluate_coefficient(self: BosonOperatorTerm, parameters: dict[str, complex] = {}) complex
Returns the evaluated coefficient of the product operator.
- is_identity()¶
- is_identity(self: BosonOperatorTerm) bool
Checks if all operators in the product are the identity. Note: 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(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: BosonOperatorTerm, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- to_sparse_matrix(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- class cudaq.operators.boson.BosonOperatorElement¶
- 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(*args, **kwargs)¶
Overloaded function.
Returns the matrix representation of the operator.
- to_matrix(self: BosonOperatorElement, dimensions: dict[int, int] = {}, \*\*kwargs) numpy.ndarray[]
Returns the matrix representation of the operator.
- to_string()¶
- to_string(self: BosonOperatorElement, include_degrees: bool) str
Returns the string representation of the operator.
- cudaq.boson.annihilate()¶
- cudaq.boson.annihilate(target: int) BosonOperatorTerm
Returns a bosonic annihilation operator on the given target index.
- cudaq.boson.canonicalized(*args, **kwargs)¶
Overloaded function.
- cudaq.boson.canonicalized(arg0: BosonOperatorTerm) BosonOperatorTerm
Removes all identity operators from the operator.
- cudaq.boson.canonicalized(arg0: BosonOperatorTerm, arg1: set[int]) 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.
- cudaq.boson.canonicalized(arg0: BosonOperator) BosonOperator
Removes all identity operators from the operator.
- cudaq.boson.canonicalized(arg0: BosonOperator, arg1: set[int]) 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.
- cudaq.boson.create()¶
- cudaq.boson.create(target: int) BosonOperatorTerm
Returns a bosonic creation operator on the given target index.
- cudaq.boson.empty()¶
- cudaq.boson.empty() BosonOperator
Returns sum operator with no terms. Note that a sum with no terms multiplied by anything still is a sum with no terms.
- cudaq.boson.identities()¶
- cudaq.boson.identities(first: int, last: int) BosonOperatorTerm
Creates a product operator that applies an identity operation to all degrees of freedom in the open range [first, last).
- cudaq.boson.identity(*args, **kwargs)¶
Overloaded function.
- cudaq.boson.identity() BosonOperatorTerm
Returns product operator with constant value 1.
- cudaq.boson.identity(target: int) BosonOperatorTerm
Returns an identity operator on the given target index.
- cudaq.boson.momentum()¶
- cudaq.boson.momentum(target: int) BosonOperator
Returns a bosonic momentum operator on the given target index.
- cudaq.boson.number()¶
- cudaq.boson.number(target: int) BosonOperatorTerm
Returns a bosonic number operator on the given target index.
- cudaq.boson.position()¶
- cudaq.boson.position(target: int) BosonOperator
Returns a bosonic position operator on the given target index.
General Operators¶
- class cudaq.operators.MatrixOperator¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: MatrixOperator) MatrixOperator
Removes all identity operators from the operator.
- canonicalize(self: MatrixOperator, arg0: set[int]) 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()¶
- copy(self: MatrixOperator) MatrixOperator
Creates a copy of the operator.
- property degrees¶
Returns a vector that lists all degrees of freedom that the operator targets.
- distribute_terms()¶
- distribute_terms(self: MatrixOperator, arg0: int) list[MatrixOperator]
Partitions the terms of the sums into the given number of separate sums.
- dump()¶
- dump(self: MatrixOperator) None
Prints the string representation of the operator to the standard output.
- static empty()¶
- empty() MatrixOperator
Creates a sum operator with no terms. And empty sum is the neutral element for addition; multiplying an empty sum with anything will still result in an empty sum.
- static identity(*args, **kwargs)¶
Overloaded function.
- identity() MatrixOperatorTerm
Creates a product operator with constant value 1. The identity operator is the neutral element for multiplication.
- identity(arg0: int) MatrixOperatorTerm
Creates a product operator that applies the identity to the given target index.
- 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(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: MatrixOperator, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- trim(*args, **kwargs)¶
Overloaded function.
- trim(self: MatrixOperator, tol: float = 0.0, parameters: dict[str, complex] = {}) MatrixOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- trim(self: MatrixOperator, tol: float = 0.0, \*\*kwargs) MatrixOperator
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance.
- class cudaq.operators.MatrixOperatorTerm¶
- canonicalize(*args, **kwargs)¶
Overloaded function.
- canonicalize(self: MatrixOperatorTerm) MatrixOperatorTerm
Removes all identity operators from the operator.
- canonicalize(self: MatrixOperatorTerm, arg0: set[int]) 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
evaluate
method.
- copy()¶
- copy(self: MatrixOperatorTerm) MatrixOperatorTerm
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()¶
- dump(self: MatrixOperatorTerm) None
Prints the string representation of the operator to the standard output.
- evaluate_coefficient()¶
- evaluate_coefficient(self: MatrixOperatorTerm, parameters: dict[str, complex] = {}) complex
Returns the evaluated coefficient of the product operator.
- is_identity()¶
- is_identity(self: MatrixOperatorTerm) bool
Checks if all operators in the product are the identity. Note: 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(*args, **kwargs)¶
Overloaded function.
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.- to_matrix(self: MatrixOperatorTerm, dimensions: dict[int, int] = {}, invert_order: bool = False, \*\*kwargs) numpy.ndarray[]
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_order
argument toTrue
. See also the documentation fordegrees
for more detail.
- class cudaq.operators.MatrixOperatorElement¶
- 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(*args, **kwargs)¶
Overloaded function.
Returns the matrix representation of the operator.
- to_matrix(self: MatrixOperatorElement, dimensions: dict[int, int] = {}, \*\*kwargs) numpy.ndarray[]
Returns the matrix representation of the operator.
- to_string()¶
- to_string(self: MatrixOperatorElement, include_degrees: bool) str
Returns the string representation of the operator.
- cudaq.operators.custom.canonicalized(*args, **kwargs)¶
Overloaded function.
- cudaq.operators.custom.canonicalized(arg0: MatrixOperatorTerm) MatrixOperatorTerm
Removes all identity operators from the operator.
- cudaq.operators.custom.canonicalized(arg0: MatrixOperatorTerm, arg1: set[int]) 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.
- cudaq.operators.custom.canonicalized(arg0: MatrixOperator) MatrixOperator
Removes all identity operators from the operator.
- cudaq.operators.custom.canonicalized(arg0: MatrixOperator, arg1: set[int]) 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.
- 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
create
function 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
create
function must take an argument calleddimension
(ordim
for short), if the operator acts on a single degree of freedom, and an argument calleddimensions
(ordims
for short), if the operator acts on multiple degrees of freedom.override – if True it allows override the definition. (default: False)
- cudaq.operators.custom.displace()¶
- cudaq.operators.custom.displace(target: int) MatrixOperatorTerm
Returns a displacement operator on the given target index.
- cudaq.operators.custom.empty()¶
- cudaq.operators.custom.empty() MatrixOperator
Returns sum operator with no terms. Note that a sum with no terms multiplied by anything still is a sum with no terms.
- cudaq.operators.custom.identities()¶
- cudaq.operators.custom.identities(first: int, last: int) MatrixOperatorTerm
Creates a product operator that applies an identity operation to all degrees of freedom in the open range [first, last).
- 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.
- cudaq.operators.custom.momentum()¶
- cudaq.operators.custom.momentum(target: int) MatrixOperatorTerm
Returns a momentum operator on the given target index.
- cudaq.operators.custom.number()¶
- cudaq.operators.custom.number(target: int) MatrixOperatorTerm
Returns a number operator on the given target index.
- cudaq.operators.custom.parity()¶
- cudaq.operators.custom.parity(target: int) MatrixOperatorTerm
Returns a parity operator on the given target index.
- cudaq.operators.custom.position()¶
- cudaq.operators.custom.position(target: int) MatrixOperatorTerm
Returns a position operator on the given target index.
- cudaq.operators.custom.squeeze()¶
- cudaq.operators.custom.squeeze(target: int) MatrixOperatorTerm
Returns a squeezing operator on the given target index.
Data Types¶
- class cudaq.SimulationPrecision¶
Enumeration describing the precision of the underyling simulation.
Members:
fp32
fp64
- property name¶
object) -> str :noindex:
- Type:
- name(self
- class cudaq.Target¶
The
cudaq.Target
represents the underlying infrastructure that CUDA-Q kernels will execute on. Instances ofcudaq.Target
describe 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()¶
- get_precision(self: Target) SimulationPrecision
Return the simulation precision for the current target.
- is_emulated()¶
-
Returns true if the emulation mode for the target has been activated.
- property name¶
The name of the
cudaq.Target
.
- property platform¶
The name of the quantum_platform implementation this
cudaq.Target
leverages.
- property simulator¶
The name of the simulator this
cudaq.Target
leverages. 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 static cudaq.State.from_data() method.- amplitude(*args, **kwargs)¶
Overloaded function.
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])
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(*args, **kwargs)¶
Overloaded function.
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]])
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'])
- static from_data(*args, **kwargs)¶
Overloaded function.
- from_data(arg0: numpy.ndarray) State
Return a state from data.
- from_data(arg0: list[numpy.ndarray]) State
Return a state from matrix product state tensor data.
Return a state from matrix product state tensor data.
Return a state from matrix product state tensor data (as CuPy ndarray).
Return a state from CuPy device array.
- getTensor()¶
-
Return the
idx
tensor making up this state representation.
- getTensors()¶
-
Return all the tensors that comprise this state representation.
- class cudaq.Tensor¶
The
Tensor
describes 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
QuakeValue
represents a handle to an individual function argument of aKernel
, or a return value from an operation within it. As documented inmake_kernel()
, aQuakeValue
can hold values of the following types: int, float, list/List,qubit
, orqvector
. TheQuakeValue
can 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
QuakeValue
type 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
QuakeValue
type 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
QuakeValue
type 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
QuakeValue
type 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
QuakeValue
type 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
QuakeValue
type 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
QuakeValue
type is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 * value
- __getitem__(idx)¶
Return the element of
self
at the providedindex
.Note
Only
list
orqvector
typeQuakeValue
’s may be indexed.- Parameters:
index (int) – The element of
self
that you’d like to return.- Returns:
A new
QuakeValue
for theindex
element ofself
.- Return type:
- Raises:
RuntimeError – if
self
is a non-subscriptableQuakeValue
.
- slice(startIdx, count)¶
Return a slice of the given
QuakeValue
as a newQuakeValue
.Note
The underlying
QuakeValue
must be alist
orveq
.- Parameters:
- Returns:
A new
QuakeValue
containing a slice ofself
from thestart
element to thestart + count
element.- Return type:
- class cudaq.qubit¶
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¶
An owning, dynamically sized container for qubits. The semantics of the
qvector
follows that of astd::vector
orlist
for qubits.
- class cudaq.ComplexMatrix¶
The
ComplexMatrix
is a thin wrapper around a matrix of complex<double> elements.- __getitem__(*args, **kwargs)¶
Overloaded function.
- __getitem__(self: ComplexMatrix, arg0: int, arg1: int) complex
Return the matrix element at i, j.
- __getitem__(self: ComplexMatrix, arg0: tuple[int, int]) complex
Return the matrix element at i, j.
- __str__()¶
- __str__(self: ComplexMatrix) str
Returns the string representation of the matrix.
- dump()¶
- dump(self: ComplexMatrix) None
Prints the matrix to the standard output.
- minimal_eigenvalue()¶
- minimal_eigenvalue(self: ComplexMatrix) complex
Return the lowest eigenvalue for this
ComplexMatrix
.
- num_columns()¶
- num_columns(self: ComplexMatrix) int
Returns the number of columns in the matrix.
- num_rows()¶
- num_rows(self: ComplexMatrix) int
Returns the number of rows in the matrix.
- to_numpy()¶
- to_numpy(self: ComplexMatrix) numpy.ndarray[]
Convert
ComplexMatrix
to numpy.ndarray.
- class cudaq.SampleResult¶
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
At this time, mid-circuit measurements are not directly supported. Mid-circuit measurements may only be used if they are passed through to
c_if
.- register_names¶
A list of the names of each measurement register that are stored in
self
.- Type:
List[str]
- __getitem__()¶
- __getitem__(self: SampleResult, bitstring: str) int
Return the measurement counts for the given
bitstring
.
- __iter__()¶
- __iter__(self: SampleResult) Iterator[str]
Iterate through the
SampleResult
dictionary.
- __len__()¶
- __len__(self: SampleResult) int
Return the number of elements in
self
. Equivalent to the number of uniquely measured bitstrings.
- clear()¶
- clear(self: SampleResult) None
Clear out all metadata from
self
.
- count()¶
- count(self: SampleResult, bitstring: str, register_name: str = '__global__') int
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(self: SampleResult, arg0: list[int]) None
Deserialize this SampleResult from an existing vector of integers adhering to the implicit encoding.
- dump()¶
- dump(self: SampleResult) None
Print a string of the raw measurement counts data to the terminal.
- expectation()¶
- expectation(self: SampleResult, register_name: str = '__global__') float
Return the expectation value in the Z-basis of the
Kernel
that was sampled.
- expectation_z()¶
- expectation_z(self: SampleResult, register_name: str = '__global__') float
Return the expectation value in the Z-basis of the
Kernel
that was sampled.
- get_marginal_counts()¶
- get_marginal_counts(self: SampleResult, marginal_indices: list[int], \*, register_name: str = '__global__') SampleResult
Extract the measurement counts data for the provided subset of qubits (
marginal_indices
).- Parameters:
- Returns:
A new
SampleResult
dictionary containing the extracted measurement data.- Return type:
- get_register_counts()¶
- get_register_counts(self: SampleResult, register_name: str) SampleResult
Extract the provided sub-register (
register_name
) as a newSampleResult
.
- get_sequential_data()¶
- get_sequential_data(self: SampleResult, register_name: str = '__global__') list[str]
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_total_shots(self: SampleResult) int
Get the total number of shots in the sample result
- items()¶
- items(self: SampleResult) Iterator[tuple[str, int]]
Return the key/value pairs in this
SampleResult
dictionary.
- most_probable()¶
- most_probable(self: SampleResult, register_name: str = '__global__') str
Return the bitstring that was measured most frequently in the experiment.
- probability()¶
- probability(self: SampleResult, bitstring: str, register_name: str = '__global__') float
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:
- serialize()¶
- serialize(self: SampleResult) list[int]
Serialize this SampleResult to a vector of integer encoding.
- values()¶
- values(self: SampleResult) Iterator[int]
Return all values (the counts) in this
SampleResult
dictionary.
- class cudaq.AsyncSampleResult¶
A data-type containing the results of a call to
sample_async()
. TheAsyncSampleResult
models a future-like type, whoseSampleResult
may be returned via an invocation of theget
method. This kicks off a wait on the current thread until the results are available. See future for more information on this programming pattern.- get()¶
- get(self: AsyncSampleResult) SampleResult
Return the
SampleResult
from the asynchronous sample execution.
- class cudaq.ObserveResult¶
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(*args, **kwargs)¶
Overloaded function.
- counts(self: ObserveResult) SampleResult
Returns a
SampleResult
dictionary with the measurement results from the experiment. The result for each individual term of thespin_operator
is stored in its own measurement register. Each register name corresponds to the string representation of the spin term (without any coefficients).- counts(self: ObserveResult, sub_term: cudaq::product_op<cudaq::spin_handler>) SampleResult
- counts(self: ObserveResult, sub_term: object) SampleResult
Given a
sub_term
of the globalspin_operator
that 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: ObserveResult, sub_term: cudaq::sum_op<cudaq::spin_handler>) SampleResult
Deprecated - ensure to pass a SpinOperatorTerm instead of a SpinOperator
- dump()¶
- dump(self: ObserveResult) None
Dump the raw data from the
SampleResult
that are stored inObserveResult
to the terminal.
- expectation(*args, **kwargs)¶
Overloaded function.
- expectation(self: ObserveResult) float
Return the expectation value of the
spin_operator
that was provided inobserve()
.- expectation(self: ObserveResult, sub_term: cudaq::product_op<cudaq::spin_handler>) float
- expectation(self: ObserveResult, sub_term: object) float
Return the expectation value of an individual
sub_term
of the globalspin_operator
that was passed toobserve()
.- Parameters:
sub_term (
SpinOperatorTerm
) – An individual sub-term of thespin_operator
.- Returns:
The expectation value of the
sub_term
with respect to theKernel
that was passed toobserve()
.- Return type:
- expectation(self: ObserveResult, sub_term: cudaq::sum_op<cudaq::spin_handler>) float
Deprecated - ensure to pass a SpinOperatorTerm instead of a SpinOperator
- get_spin()¶
- get_spin(self: ObserveResult) cudaq::sum_op<cudaq::spin_handler>
Return the
SpinOperator
corresponding to thisObserveResult
.
- class cudaq.AsyncObserveResult¶
A data-type containing the results of a call to
observe_async()
.The
AsyncObserveResult
contains a future, whoseObserveResult
may be returned via an invocation of theget
method.This kicks off a wait on the current thread until the results are available.
See future for more information on this programming pattern.
- get()¶
- get(self: AsyncObserveResult) ObserveResult
Returns the
ObserveResult
from the asynchronous observe execution.
- class cudaq.AsyncStateResult¶
A data-type containing the results of a call to
get_state_async()
. TheAsyncStateResult
models a future-like type, whoseState
may be returned via an invocation of theget
method. This kicks off a wait on the current thread until the results are available. See future for more information on this programming pattern.- get()¶
- get(self: AsyncStateResult) State
Return the
State
from the asynchronousget_state
accessor execution.
- class cudaq.OptimizationResult¶
- class cudaq.EvolveResult¶
Stores the execution data from an invocation of
evolve()
.- expectation_values()¶
- expectation_values(self: EvolveResult) Optional[list[list[ObserveResult]]]
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()¶
- final_expectation_values(self: EvolveResult) Optional[list[list[ObserveResult]]]
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.
- final_state()¶
- final_state(self: EvolveResult) State
Stores the final state produced by a call to
evolve()
. Represent the state of a quantum system after time evolution under a set of operators, see theevolve()
documentation for more detail.
- intermediate_states()¶
- intermediate_states(self: EvolveResult) Optional[list[State]]
Stores all intermediate states, meaning the state after each step in a defined schedule, produced by a call to
evolve()
, including the final state. This property is only populated if saving intermediate results was requested in the call toevolve()
.
- class cudaq.AsyncEvolveResult¶
Stores the execution data from an invocation of
evolve_async()
.- get()¶
- get(self: AsyncEvolveResult) EvolveResult
Retrieve the evolution result from the asynchronous evolve execution .
Optimizers¶
- class cudaq.optimizers.optimizer¶
- class cudaq.optimizers.GradientDescent¶
- static from_json()¶
- from_json(arg0: str) optimizers.GradientDescent
Convert JSON string to optimizer
- property initial_parameters¶
Set the initial parameter values for the optimization.
- property lower_bounds¶
Set the lower value bound for the optimization parameters.
- property max_iterations¶
Set the maximum number of optimizer iterations.
- optimize()¶
- optimize(self: optimizers.GradientDescent, dimensions: int, function: Callable) tuple[float, list[float]]
Run
cudaq.optimize()
on the provided objective function.
- requires_gradients()¶
- requires_gradients(self: optimizers.GradientDescent) bool
Returns whether the optimizer requires gradient.
- to_json()¶
- to_json(self: optimizers.GradientDescent) str
Convert optimizer to JSON string
- property upper_bounds¶
Set the upper value bound for the optimization parameters.
- class cudaq.optimizers.COBYLA¶
- static from_json()¶
- from_json(arg0: str) optimizers.COBYLA
Convert JSON string to optimizer
- property initial_parameters¶
Set the initial parameter values for the optimization.
- property lower_bounds¶
Set the lower value bound for the optimization parameters.
- property max_iterations¶
Set the maximum number of optimizer iterations.
- optimize()¶
-
Run
cudaq.optimize()
on the provided objective function.
- requires_gradients()¶
- requires_gradients(self: optimizers.COBYLA) bool
Returns whether the optimizer requires gradient.
- to_json()¶
- to_json(self: optimizers.COBYLA) str
Convert optimizer to JSON string
- property upper_bounds¶
Set the upper value bound for the optimization parameters.
- class cudaq.optimizers.NelderMead¶
- static from_json()¶
- from_json(arg0: str) optimizers.NelderMead
Convert JSON string to optimizer
- property initial_parameters¶
Set the initial parameter values for the optimization.
- property lower_bounds¶
Set the lower value bound for the optimization parameters.
- property max_iterations¶
Set the maximum number of optimizer iterations.
- optimize()¶
- optimize(self: optimizers.NelderMead, dimensions: int, function: Callable) tuple[float, list[float]]
Run
cudaq.optimize()
on the provided objective function.
- requires_gradients()¶
- requires_gradients(self: optimizers.NelderMead) bool
Returns whether the optimizer requires gradient.
- to_json()¶
- to_json(self: optimizers.NelderMead) str
Convert optimizer to JSON string
- property upper_bounds¶
Set the upper value bound for the optimization parameters.
- class cudaq.optimizers.LBFGS¶
- static from_json()¶
- from_json(arg0: str) optimizers.LBFGS
Convert JSON string to optimizer
- property initial_parameters¶
Set the initial parameter values for the optimization.
- property lower_bounds¶
Set the lower value bound for the optimization parameters.
- property max_iterations¶
Set the maximum number of optimizer iterations.
- optimize()¶
-
Run
cudaq.optimize()
on the provided objective function.
- requires_gradients()¶
- requires_gradients(self: optimizers.LBFGS) bool
Returns whether the optimizer requires gradient.
- to_json()¶
- to_json(self: optimizers.LBFGS) str
Convert optimizer to JSON string
- property upper_bounds¶
Set the upper value bound for the optimization parameters.
Gradients¶
- class cudaq.gradients.gradient¶
- class cudaq.gradients.CentralDifference¶
- compute()¶
- compute(self: gradients.gradient, parameter_vector: list[float], function: Callable, funcAtX: float) list[float]
Compute the gradient of the provided
parameter_vector
with respect to its loss function, using theCentralDifference
method.
- static from_json()¶
- from_json(arg0: str) gradients.CentralDifference
Convert JSON string to gradient
- to_json()¶
- to_json(self: gradients.CentralDifference) str
Convert gradient to JSON string
- class cudaq.gradients.ForwardDifference¶
- compute()¶
- compute(self: gradients.gradient, parameter_vector: list[float], function: Callable, funcAtX: float) list[float]
Compute the gradient of the provided
parameter_vector
with respect to its loss function, using theForwardDifference
method.
- static from_json()¶
- from_json(arg0: str) gradients.ForwardDifference
Convert JSON string to gradient
- to_json()¶
- to_json(self: gradients.ForwardDifference) str
Convert gradient to JSON string
- class cudaq.gradients.ParameterShift¶
- compute()¶
- compute(self: gradients.gradient, parameter_vector: list[float], function: Callable, funcAtX: float) list[float]
Compute the gradient of the provided
parameter_vector
with respect to its loss function, using theParameterShift
method.
- static from_json()¶
- from_json(arg0: str) gradients.ParameterShift
Convert JSON string to gradient
- to_json()¶
- to_json(self: gradients.ParameterShift) str
Convert gradient to JSON string
Noisy Simulation¶
- class cudaq.NoiseModel¶
The
NoiseModel
defines a set ofKrausChannel
’s applied to specific qubits after the invocation of specified quantum operations.- __init__()¶
- __init__(self: NoiseModel) None
Construct a noise model with all built-in channels pre-registered.
- add_all_qubit_channel()¶
- add_all_qubit_channel(self: NoiseModel, operator: str, channel: cudaq.KrausChannel, num_controls: int = 0) None
Add the given
KrausChannel
to 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
KrausChannel
to apply to the specifiedoperator
on any arbitrary qubits.num_controls – Number of control bits. Default is 0 (no control bits).
- add_channel(*args, **kwargs)¶
Overloaded function.
- add_channel(self: NoiseModel, operator: str, qubits: list[int], channel: cudaq.KrausChannel) None
Add the given
KrausChannel
to 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
KrausChannel
to apply to the specifiedoperator
on the specifiedqubits
.
- add_channel(self: NoiseModel, operator: str, pre: Callable[[list[int], list[float]], cudaq.KrausChannel]) None
Add the given
KrausChannel
generator 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
KrausChannel
to apply to the specifiedoperator
.
- get_channels()¶
- get_channels(self: NoiseModel, operator: str, qubits: list[int]) list[cudaq.KrausChannel]
Return the
KrausChannel
’s that make up this noise model.
- class cudaq.BitFlipChannel¶
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__(*args, **kwargs)¶
Overloaded function.
- __init__(self: BitFlipChannel, arg0: list[float]) None
- __init__(self: BitFlipChannel, probability: float) None
Initialize the
BitFlipChannel
with the providedprobability
.
- class cudaq.PhaseFlipChannel¶
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__(*args, **kwargs)¶
Overloaded function.
- __init__(self: PhaseFlipChannel, arg0: list[float]) None
- __init__(self: PhaseFlipChannel, probability: float) None
Initialize the
PhaseFlipChannel
with the providedprobability
.
- class cudaq.DepolarizationChannel¶
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__(*args, **kwargs)¶
Overloaded function.
- __init__(self: DepolarizationChannel, arg0: list[float]) None
- __init__(self: DepolarizationChannel, probability: float) None
Initialize the
DepolarizationChannel
with the providedprobability
.
- class cudaq.AmplitudeDampingChannel¶
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 probablity that the qubit will decay to its ground state. The probability of the qubit remaining in the same state is therefore1 - probability
.- __init__(*args, **kwargs)¶
Overloaded function.
- __init__(self: AmplitudeDampingChannel, arg0: list[float]) None
- __init__(self: AmplitudeDampingChannel, probability: float) None
Initialize the
AmplitudeDampingChannel
with the providedprobability
.
- class cudaq.PhaseDamping¶
A Kraus channel that models the single-qubit phase damping error. This is similar to AmplitudeDamping, but for phase.
- class cudaq.XError¶
A Pauli error that applies the X operator when an error occurs. It is the same as BitFlipChannel.
- class cudaq.YError¶
A Pauli error that applies the Y operator when an error occurs.
- class cudaq.ZError¶
A Pauli error that applies the Z operator when an error occurs. It is the same as PhaseFlipChannel.
- class cudaq.Pauli1¶
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¶
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¶
The same as DepolarizationChannel (single qubit depolarization)
- class cudaq.Depolarization2¶
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¶
The
KrausChannel
is composed of a list ofKrausOperator
’s and is applied to a specific qubit or set of qubits.- __getitem__()¶
- __getitem__(self: KrausChannel, index: int) KrausOperator
Return the
KrausOperator
at the given index in thisKrausChannel
.
- append()¶
- append(self: KrausChannel, arg0: KrausOperator) None
Add a
KrausOperator
to thisKrausChannel
.
- class cudaq.KrausOperator¶
The
KrausOperator
is 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(*args, **kwargs)¶
Overloaded function.
Gather and scatter the
local
list of floating-point numbers, returning a concatenation of all lists across all ranks. The total global list size must be provided.Gather and scatter the
local
list of integers, returning a concatenation of all lists across all ranks. The total global list size must be provided.
- cudaq.mpi.broadcast()¶
-
Broadcast an array from a process (rootRank) to all other processes. The size of broadcast array must be provided.
ORCA Submodule¶
- cudaq.orca.sample(*args, **kwargs)¶
Overloaded function.
Performs Time Bin Interferometer (TBI) boson sampling experiments on ORCA’s backends
Performs Time Bin Interferometer (TBI) boson sampling experiments on ORCA’s backends