CUDA-Q Python API¶
Program Construction¶
- cudaq.make_kernel(*args)¶
 Create a
Kernel: An empty kernel function to be used for quantum program construction. This kernel is non-parameterized if it accepts no arguments, else takes the provided types as arguments.Returns a kernel if it is non-parameterized, else a tuple containing the kernel and a
QuakeValuefor each kernel argument.# Example: # Non-parameterized kernel. kernel = cudaq.make_kernel() # Example: # Parameterized kernel that accepts an `int` and `float` as arguments. kernel, int_value, float_value = cudaq.make_kernel(int, float)
- class cudaq.PyKernel(argTypeList)¶
 The
Kernelprovides an API for dynamically constructing quantum circuits. TheKernelprogrammatically represents the circuit as an MLIR function using the Quake dialect.- arguments¶
 The arguments accepted by the
Kernelfunction. Read-only.- Type:
 List[
QuakeValue]
- class cudaq.PyKernelDecorator(function, verbose=False, module=None, kernelName=None)¶
 The
PyKernelDecoratorserves 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
ExecutionEnginefor 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.
- __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.
- cudaq.kernel(function=None, **kwargs)¶
 The
cudaq.kernelrepresents the CUDA-Q language function attribute that programmers leverage to indicate the following function is a CUDA-Q kernel and should be compile and executed on an available quantum coprocessor.Verbose logging can be enabled via
verbose=True.
Kernel Execution¶
- cudaq.sample(kernel, *args, shots_count=1000, noise_model=None)¶
 Sample the state generated by the provided
kernelat the given kernelargumentsover the specified number of circuit executions (shots_count). Each argument inargumentsprovided can be a list orndarrayof arguments of the specified kernel argument type, and in this case, thesamplefunctionality will be broadcasted over all argument sets and a list ofsample_resultinstances will be returned.- Parameters:
 kernel (
Kernel) – TheKernelto executeshots_counttimes on the QPU.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments. For example, if the kernel takes two
floatvalues as input, thesamplecall should be structured ascudaq.sample(kernel, firstFloat, secondFloat). For broadcasting of thesamplefunction, the arguments should be structured as alistorndarrayof argument values of the specified kernel argument type.shots_count (Optional[int]) – The number of kernel executions on the QPU. Defaults to 1000. Key-word only.
noise_model (Optional[
NoiseModel]) – The optionalNoiseModelto add noise to the kernel execution on the simulator. Defaults to an empty noise model.
- Returns:
 A dictionary containing the measurement count results for the
Kernel, or a list of such results in the case ofsamplefunction broadcasting.- Return type:
 SampleResultorlist[SampleResult]
- cudaq.sample_async()¶
 - cudaq.sample_async(kernel: object, \*args, shots_count: int = 1000, qpu_id: int = 0) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncSampleResult
 
Asynchronously sample the state of the provided
kernelat the specified number of circuit executions (shots_count). When targeting a quantum platform with more than one QPU, the optionalqpu_idallows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get().- Parameters:
 kernel (
Kernel) – TheKernelto executeshots_counttimes on the QPU.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
shots_count (Optional[int]) – The number of kernel executions on the QPU. Defaults to 1000. Key-word only.
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, execution=None)¶
 Compute the expected value of the
spin_operatorwith respect to thekernel. If the inputspin_operatoris a list ofSpinOperatorthen compute the expected value of every operator in the list and return a list of results. If the kernel accepts arguments, it will be evaluated with respect tokernel(*arguments). Each argument inargumentsprovided can be a list orndarrayof arguments of the specified kernel argument type, and in this case, theobservefunctionality will be broadcasted over all argument sets and a list ofobserve_resultinstances will be returned. If both the inputspin_operatorandargumentsare broadcast lists, a nested list of results overargumentsthenspin_operatorwill be returned.- Parameters:
 kernel (
Kernel) – TheKernelto evaluate the expectation value with respect to.spin_operator (
SpinOperatororlist[SpinOperator]) – The Hermitian spin operator to calculate the expectation of, or a list of such operators.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
shots_count (Optional[int]) – The number of shots to use for QPU execution. Defaults to -1 implying no shots-based sampling. Key-word only.
noise_model (Optional[
NoiseModel]) – The optionalNoiseModelto add noise to the kernel execution on the simulator. Defaults to an empty noise model.
- Returns:
 A data-type containing the expectation value of the
spin_operatorwith respect to thekernel(*arguments), or a list of such results in the case ofobservefunction broadcasting. Ifshots_countwas provided, theObserveResultwill also contain aSampleResultdictionary.- Return type:
 
- cudaq.observe_async()¶
 - cudaq.observe_async(kernel: object, spin_operator: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, \*args, qpu_id: int = 0, shots_count: int = -1) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncObserveResult
 
Compute the expected value of the
spin_operatorwith respect to thekernelasynchronously. If the kernel accepts arguments, it will be evaluated with respect tokernel(*arguments). When targeting a quantum platform with more than one QPU, the optionalqpu_idallows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get().- Parameters:
 kernel (
Kernel) – TheKernelto evaluate the expectation value with respect to.spin_operator (
SpinOperator) – The Hermitian spin operator to calculate the expectation of.*arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
qpu_id (Optional[int]) – The optional identification for which QPU on the platform to target. Defaults to zero. Key-word only.
shots_count (Optional[int]) – The number of shots to use for QPU execution. Defaults to -1 implying no shots-based sampling. Key-word only.
- Returns:
 A future containing the result of the call to observe.
- Return type:
 
- cudaq.get_state()¶
 - cudaq.get_state(arg0: object, \*args) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State
 
Return the
Stateof the system after execution of the providedkernel.- Parameters:
 
# Example: import numpy as np # Define a kernel that will produced the all |11...1> state. 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) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncStateResult
 
Asynchronously retrieve the state generated by the given quantum kernel. When targeting a quantum platform with more than one QPU, the optional
qpu_idallows for control over which QPU to enable. Will return a future whose results can be retrieved viafuture.get().- Parameters:
 *arguments (Optional[Any]) – The concrete values to evaluate the kernel function at. Leave empty if the kernel doesn’t accept any arguments.
qpu_id (Optional[int]) – The optional identification for which QPU on the platform to target. Defaults to zero. Key-word only.
- Returns:
 Quantum state (state vector or density matrix) data).
- Return type:
 
- cudaq.vqe(*args, **kwargs)¶
 Overloaded function.
- cudaq.vqe(kernel: object, spin_operator: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, optimizer: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.optimizer, parameter_count: int, shots: int = -1) tuple[float, list[float]]
 
- cudaq.vqe(kernel: object, spin_operator: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, optimizer: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.optimizer, parameter_count: int, argument_mapper: Callable, shots: int = -1) tuple[float, list[float]]
 
- cudaq.vqe(kernel: object, gradient_strategy: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.gradients.gradient, spin_operator: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, optimizer: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.optimizer, parameter_count: int, shots: int = -1) tuple[float, list[float]]
 
- cudaq.vqe(kernel: object, gradient_strategy: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.gradients.gradient, spin_operator: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, optimizer: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.optimizer, parameter_count: int, argument_mapper: Callable, shots: int = -1) tuple[float, list[float]]
 
- cudaq.draw()¶
 - 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) ├ # ╰───╯╰──────────╯
Backend Configuration¶
- cudaq.has_target()¶
 - 
Return true if the
cudaq.Targetwith the given name exists. 
- cudaq.get_target(*args, **kwargs)¶
 Overloaded function.
- cudaq.get_target(arg0: str) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target
 
Return the
cudaq.Targetwith the given name. Will raise an exception if the name is not valid.- cudaq.get_target() cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target
 
Return the
cudaq.Targetwith the given name. Will raise an exception if the name is not valid.
- cudaq.get_targets()¶
 - cudaq.get_targets() list[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target]
 
Return all available
cudaq.Targetinstances on the current system.
- cudaq.set_target(*args, **kwargs)¶
 Overloaded function.
- cudaq.set_target(arg0: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target, \*\*kwargs) None
 
Set the
cudaq.Targetto be used for CUDA-Q kernel execution. Can provide optional, target-specific configuration data via Python kwargs.- cudaq.set_target(arg0: str, \*\*kwargs) None
 
Set the
cudaq.Targetwith given name to be used for CUDA-Q kernel execution. Can provide optional, target-specific configuration data via Python kwargs.
- cudaq.set_noise()¶
 - 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.initialize_cudaq()¶
 - cudaq.initialize_cudaq(\*\*kwargs) None
 
Initialize the CUDA-Q environment.
Data Types¶
- class cudaq.Target¶
 The
cudaq.Targetrepresents the underlying infrastructure that CUDA-Q kernels will execute on. Instances ofcudaq.Targetdescribe what simulator they may leverage, the quantum_platform required for execution, and a description for the target.- property description¶
 A string describing the features for this
cudaq.Target.
- is_emulated()¶
 - is_emulated(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target) bool
 
Returns true if the emulation mode for the target has been activated.
- is_remote()¶
 - is_remote(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target) bool
 
Returns true if the target consists of a remote REST QPU.
- property name¶
 The name of the
cudaq.Target.
- num_qpus()¶
 - num_qpus(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.Target) int
 
Return the number of QPUs available in this
cudaq.Target.
- property platform¶
 The name of the quantum_platform implementation this
cudaq.Targetleverages.
- property simulator¶
 The name of the simulator this
cudaq.Targetleverages. This will be empty for physical QPUs.
- class cudaq.State¶
 A data-type representing the quantum state of the internal simulator. Returns a state vector by default. If the target is set to
density-matrix-cpu, a density matrix will be returned.- dump()¶
 - 
Print the state to the console.
 
- overlap(*args, **kwargs)¶
 Overloaded function.
Compute the overlap between the provided
State’s.- overlap(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State, arg0: numpy.ndarray) float
 
Compute the overlap between the provided
State’s.
- class cudaq.QuakeValue(mlirValue, pyKernel, size=None)¶
 A
QuakeValuerepresents a handle to an individual function argument of aKernel, or a return value from an operation within it. As documented inmake_kernel(), aQuakeValuecan hold values of the following types: int, float, list/List,qubit, orqvector. TheQuakeValuecan also hold kernel operations such as qubit allocations and measurements.- __add__(other)¶
 Return the sum of
self(QuakeValue) andother(float).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = value + 5.0
- __radd__(other)¶
 Return the sum of
other(float) andself(QuakeValue).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 + value
- __sub__(other)¶
 Return the difference of
self(QuakeValue) andother(float).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = value - 5.0
- __rsub__(other)¶
 Return the difference of
other(float) andself(QuakeValue).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 - value
- __neg__()¶
 Return the negation of
self(QuakeValue).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = -value
- __mul__(other)¶
 Return the product of
self(QuakeValue) withother(float).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = value * 5.0
- __rmul__(other)¶
 Return the product of
other(float) withself(QuakeValue).- Raises:
 RuntimeError – if the underlying
QuakeValuetype is not a float.
# Example: kernel, value = cudaq.make_kernel(float) new_value: QuakeValue = 5.0 * value
- __getitem__(idx)¶
 Return the element of
selfat the providedindex.Note
Only
listorqvectortypeQuakeValue’s may be indexed.- Parameters:
 index (int) – The element of
selfthat you’d like to return.- Returns:
 A new
QuakeValuefor theindexelement ofself.- Return type:
 - Raises:
 RuntimeError – if
selfis a non-subscriptableQuakeValue.
- slice(startIdx, count)¶
 Return a slice of the given
QuakeValueas a newQuakeValue.Note
The underlying
QuakeValuemust be alistorveq.- Parameters:
 - Returns:
 A new
QuakeValuecontaining a slice ofselffrom thestartelement to thestart + countelement.- Return type:
 
- class cudaq.qubit¶
 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
qvectorfollows that of astd::vectororlistfor qubits.
- class cudaq.ComplexMatrix¶
 The
ComplexMatrixis a thin wrapper around a matrix of complex<double> elements.- __getitem__(*args, **kwargs)¶
 Overloaded function.
- __getitem__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ComplexMatrix, arg0: int, arg1: int) complex
 
Return the matrix element at i, j.
- __getitem__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ComplexMatrix, arg0: tuple[int, int]) complex
 
Return the matrix element at i, j.
- __str__()¶
 - 
Write this matrix to a string representation.
 
- minimal_eigenvalue()¶
 - minimal_eigenvalue(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ComplexMatrix) complex
 
Return the lowest eigenvalue for this
ComplexMatrix.
- class cudaq.SpinOperator¶
 - __eq__()¶
 - __eq__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, other: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) bool
 
Return true if the two
SpinOperator’s are equal. Equality does not consider the coefficients.
- __add__(*args, **kwargs)¶
 Overloaded function.
Add the given
SpinOperatorto this one and return result as a newSpinOperator.Add a double to the given
SpinOperatorand return result as a newSpinOperator.
- __radd__()¶
 - __radd__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, other: float) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator
 
Add a
SpinOperatorto the given double and return result as a newSpinOperator.
- __sub__(*args, **kwargs)¶
 Overloaded function.
Subtract the given
SpinOperatorfrom this one and return result as a newSpinOperator.Subtract a double from the given
SpinOperatorand return result as a newSpinOperator.
- __rsub__()¶
 - __rsub__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, other: float) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator
 
Subtract a
SpinOperatorfrom the given double and return result as a newSpinOperator.
- __mul__(*args, **kwargs)¶
 Overloaded function.
Multiply the given
SpinOperator’s together and return result as a newSpinOperator.Multiply the
SpinOperatorby the given double and return result as a newSpinOperator.Multiply the
SpinOperatorby the given complex value and return result as a newSpinOperator.
- __rmul__(*args, **kwargs)¶
 Overloaded function.
Multiply the double by the given
SpinOperatorand return result as a newSpinOperator.Multiply the complex value by the given
SpinOperatorand return result as a newSpinOperator.
- __iter__()¶
 - __iter__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) Iterator[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator]
 
Loop through each term of this
SpinOperator.
- distribute_terms()¶
 - distribute_terms(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, chunk_count: int) list[cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator]
 
Return a list of
SpinOperatorrepresenting a distribution of the terms in thisSpinOperatorintochunk_countsized chunks.
- dump()¶
 - 
Print a string representation of this
SpinOperator. 
- for_each_pauli()¶
 - for_each_pauli(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, function: Callable) None
 
For a single
SpinOperatorterm, apply the given function to each pauli element in the term. The function must havevoid(pauli, int)signature wherepauliis the Pauli matrix type and theintis the qubit index.
- for_each_term()¶
 - for_each_term(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, function: Callable) None
 
Apply the given function to all terms in this
SpinOperator. The input function must havevoid(SpinOperator)signature.
- static from_word()¶
 - from_word(word: str) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator
 
Return a
SpinOperatorcorresponding to the provided Pauliword.# Example: # The first and third qubits will receive a Pauli X, # while the second qubit will receive a Pauli Y. word = "XYX" # Convert word to spin operator. spin_operator = cudaq.SpinOperator.from_word(word) print(spin_operator) # prints: `[1+0j] XYX`
- get_coefficient()¶
 - get_coefficient(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) complex
 
Return the coefficient of this
SpinOperator. Must be aSpinOperatorwith one term, otherwise an exception is thrown.
- get_qubit_count()¶
 - get_qubit_count(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) int
 
Return the number of qubits this
SpinOperatoris on.
- get_raw_data()¶
 - get_raw_data(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) tuple[list[list[bool]], list[complex]]
 
Return the raw data of this
SpinOperator.
- get_term_count()¶
 - get_term_count(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) int
 
Return the number of terms in this
SpinOperator.
- is_identity()¶
 - is_identity(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) bool
 
Returns a bool indicating if this
SpinOperatoris equal to the identity.
- static random()¶
 - random(qubit_count: int, term_count: int, seed: int = 1369235722) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator
 
Return a random
SpinOperatoron the given number of qubits (qubit_count) and composed of the given number of terms (term_count). An optional seed value may also be provided.
- serialize()¶
 - serialize(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) list[float]
 
Return a serialized representation of the
SpinOperator. Specifically, this encoding is via a vector of doubles. The encoding is as follows: for each term, a list of doubles where the ith element is a 3.0 for a Y, a 1.0 for a X, and a 2.0 for a Z on qubit i, followed by the real and imaginary part of the coefficient. Each term is appended to the array forming one large 1d array of doubles. The array is ended with the total number of terms represented as a double.
- to_matrix()¶
 - to_matrix(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ComplexMatrix
 
Return
selfas aComplexMatrix.
- to_sparse_matrix()¶
 - to_sparse_matrix(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator) tuple[list[complex], list[int], list[int]]
 
Return
selfas a sparse matrix. This representation is aTuple[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.
- to_string()¶
 - to_string(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SpinOperator, print_coefficient: bool = True) str
 
Return a string representation of this
SpinOperator.
- spin.i()¶
 - i(target: int) cudaq.SpinOperator
 
Return an identity
SpinOperatoron the given target qubit index.
- spin.x()¶
 - x(target: int) cudaq.SpinOperator
 
Return an X
SpinOperatoron the given target qubit index.
- spin.y()¶
 - y(target: int) cudaq.SpinOperator
 
Return a Y
SpinOperatoron the given target qubit index.
- spin.z()¶
 - z(target: int) cudaq.SpinOperator
 
Return a Z
SpinOperatoron the given target qubit index.
- 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: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult, bitstring: str) int
 
Return the measurement counts for the given
bitstring.
- __iter__()¶
 - __iter__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult) Iterator[str]
 
Iterate through the
SampleResultdictionary.
- __len__()¶
 - 
Return the number of elements in
self. Equivalent to the number of uniquely measured bitstrings. 
- clear()¶
 - 
Clear out all metadata from
self. 
- count()¶
 - count(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.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:
 
- dump()¶
 - 
Print a string of the raw measurement counts data to the terminal.
 
- expectation()¶
 - expectation(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult, register_name: str = '__global__') float
 
Return the expectation value in the Z-basis of the
Kernelthat was sampled.
- expectation_z()¶
 - expectation_z(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult, register_name: str = '__global__') float
 
Return the expectation value in the Z-basis of the
Kernelthat was sampled.
- get_marginal_counts()¶
 - get_marginal_counts(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult, marginal_indices: list[int], \*, register_name: str = '__global__') cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
 
Extract the measurement counts data for the provided subset of qubits (
marginal_indices).- Parameters:
 - Returns:
 A new
SampleResultdictionary containing the extracted measurement data.- Return type:
 
- get_register_counts()¶
 - get_register_counts(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult, register_name: str) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
 
Extract the provided sub-register (
register_name) as a newSampleResult.
- get_sequential_data()¶
 - get_sequential_data(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.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.
- items()¶
 - items(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult) Iterator[tuple[str, int]]
 
Return the key/value pairs in this
SampleResultdictionary.
- most_probable()¶
 - most_probable(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult, register_name: str = '__global__') str
 
Return the bitstring that was measured most frequently in the experiment.
- probability()¶
 - probability(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.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:
 
- values()¶
 - values(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult) Iterator[int]
 
Return all values (the counts) in this
SampleResultdictionary.
- class cudaq.AsyncSampleResult¶
 A data-type containing the results of a call to
sample_async(). TheAsyncSampleResultmodels a future-like type, whoseSampleResultmay be returned via an invocation of thegetmethod. This kicks off a wait on the current thread until the results are available. See future for more information on this programming pattern.- get()¶
 - get(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncSampleResult) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.SampleResult
 
Return the
SampleResultfrom 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.
Returns a
SampleResultdictionary with the measurement results from the experiment. The result for each individual term of thespin_operatoris stored in its own measurement register. Each register name corresponds to the string representation of the spin term (without any coefficients).Given a
sub_termof the globalspin_operatorthat was passed toobserve(), return its measurement counts.- Parameters:
 sub_term (
SpinOperator) – An individual sub-term of thespin_operator.- Returns:
 The measurement counts data for the individual
sub_term.- Return type:
 
- dump()¶
 - 
Dump the raw data from the
SampleResultthat are stored inObserveResultto the terminal. 
- expectation(*args, **kwargs)¶
 Overloaded function.
- expectation(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ObserveResult) float
 
Return the expectation value of the
spin_operatorthat was provided inobserve().- expectation(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ObserveResult, sub_term: cudaq.SpinOperator) float
 
Return the expectation value of an individual
sub_termof the globalspin_operatorthat was passed toobserve().- Parameters:
 sub_term (
SpinOperator) – An individual sub-term of thespin_operator.- Returns:
 The expectation value of the
sub_termwith respect to theKernelthat was passed toobserve().- Return type:
 
- expectation_z(*args, **kwargs)¶
 Overloaded function.
- expectation_z(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ObserveResult) float
 
Return the expectation value of the
spin_operatorthat was provided inobserve().Note
expectation_zhas been deprecated in favor ofexpectation.- expectation_z(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ObserveResult, sub_term: cudaq.SpinOperator) float
 
Return the expectation value of an individual
sub_termof the globalspin_operatorthat was passed toobserve().Note
expectation_zhas been deprecated in favor ofexpectation.- Parameters:
 sub_term (
SpinOperator) – An individual sub-term of thespin_operator.- Returns:
 The expectation value of the
sub_termwith respect to theKernelthat was passed toobserve().- Return type:
 
- get_spin()¶
 - 
Return the
SpinOperatorcorresponding to thisObserveResult. 
- class cudaq.AsyncObserveResult¶
 A data-type containing the results of a call to
observe_async().The
AsyncObserveResultcontains a future, whoseObserveResultmay be returned via an invocation of thegetmethod.This kicks off a wait on the current thread until the results are available.
See future for more information on this programming pattern.
- get()¶
 - get(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncObserveResult) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.ObserveResult
 
Returns the
ObserveResultfrom the asynchronous observe execution.
- class cudaq.AsyncStateResult¶
 A data-type containing the results of a call to
get_state_async(). TheAsyncStateResultmodels a future-like type, whoseStatemay be returned via an invocation of thegetmethod. This kicks off a wait on the current thread until the results are available. See future for more information on this programming pattern.- get()¶
 - get(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncStateResult) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State
 
Return the
Statefrom the asynchronousget_stateaccessor execution.
- class cudaq.OptimizationResult¶
 
Optimizers¶
- class cudaq.optimizers.optimizer¶
 
- class cudaq.optimizers.GradientDescent¶
 - 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: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.GradientDescent, dimensions: int, function: Callable) tuple[float, list[float]]
 
Run
cudaq.optimize()on the provided objective function.
- property upper_bounds¶
 Set the upper value bound for the optimization parameters.
- class cudaq.optimizers.COBYLA¶
 - 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: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.COBYLA, dimensions: int, function: Callable) tuple[float, list[float]]
 
Run
cudaq.optimize()on the provided objective function.
- property upper_bounds¶
 Set the upper value bound for the optimization parameters.
- class cudaq.optimizers.NelderMead¶
 - 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: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.NelderMead, dimensions: int, function: Callable) tuple[float, list[float]]
 
Run
cudaq.optimize()on the provided objective function.
- property upper_bounds¶
 Set the upper value bound for the optimization parameters.
- class cudaq.optimizers.LBFGS¶
 - 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: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.optimizers.LBFGS, dimensions: int, function: Callable) tuple[float, list[float]]
 
Run
cudaq.optimize()on the provided objective function.
- property upper_bounds¶
 Set the upper value bound for the optimization parameters.
Gradients¶
- class cudaq.gradients.gradient¶
 
- class cudaq.gradients.CentralDifference¶
 
- class cudaq.gradients.ForwardDifference¶
 
- class cudaq.gradients.ParameterShift¶
 
Noisy Simulation¶
- class cudaq.NoiseModel¶
 The
NoiseModeldefines a set ofKrausChannel’s applied to specific qubits after the invocation of specified quantum operations.- __init__()¶
 - __init__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.NoiseModel) None
 
Construct an empty noise model.
- add_channel()¶
 - add_channel(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.NoiseModel, operator: str, qubits: list[int], channel: cudaq.KrausChannel) None
 
Add the given
KrausChannelto be applied after invocation of the specified quantum operation.- Parameters:
 operator (str) – The quantum operator to apply the noise channel to.
qubits (List[int]) – The qubit/s to apply the noise channel to.
channel (cudaq.KrausChannel) – The
KrausChannelto apply to the specifiedoperatoron the specifiedqubits.
- get_channels()¶
 - get_channels(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.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 probability of the qubit remaining in the same state is therefore1 - probability.- __init__()¶
 - __init__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.BitFlipChannel, probability: float) None
 
Initialize the
BitFlipChannelwith 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 probability of the qubit phase remaining untouched is therefore1 - probability.- __init__()¶
 - __init__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.PhaseFlipChannel, probability: float) None
 
Initialize the
PhaseFlipChannelwith 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>. Its constructor expects a float value,probability, representing the probability that this decay will occur. The qubit will remain untouched, therefore, with a probability of1 - probability.- __init__()¶
 - __init__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.DepolarizationChannel, probability: float) None
 
Initialize the
DepolarizationChannelwith the providedprobability.
- class cudaq.AmplitudeDampingChannel¶
 Models the dissipation of energy due to system interactions with the environment. 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__()¶
 - __init__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AmplitudeDampingChannel, probability: float) None
 
Initialize the
AmplitudeDampingChannelwith the providedprobability.
- class cudaq.KrausChannel¶
 The
KrausChannelis composed of a list ofKrausOperator’s and is applied to a specific qubit or set of qubits.- __getitem__()¶
 - __getitem__(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.KrausChannel, index: int) cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.KrausOperator
 
Return the
KrausOperatorat the given index in thisKrausChannel.
- append()¶
 - append(self: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.KrausChannel, arg0: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.KrausOperator) None
 
Add a
KrausOperatorto thisKrausChannel.
- class cudaq.KrausOperator¶
 The
KrausOperatoris represented by a matrix and serves as an element of a quantum channel such thatSum Ki Ki^dag = I.- property col_count¶
 The number of columns in the matrix representation of this
KrausOperator.
- property row_count¶
 The number of rows in the matrix representation of this
KrausOperator.
MPI Submodule¶
- cudaq.mpi.all_gather(*args, **kwargs)¶
 Overloaded function.
Gather and scatter the
locallist of floating-point numbers, returning a concatenation of all lists across all ranks. The total global list size must be provided.Gather and scatter the
locallist 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.