CUDA-Q C++ API¶
Operators¶
-
class scalar_callback¶
A callback wrapper that encapsulates a user-provided function taking a set of complex parameters and returning a complex result.
Public Functions
-
template<typename Callable, std::enable_if_t<std::is_invocable_r_v<std::complex<double>, Callable, const std::unordered_map<std::string, std::complex<double>>&>, bool> = true>
inline scalar_callback(Callable &&callable)¶ Constructs a scalar callback from a callable object.
- Template Parameters:
Callable – The type of the callable object. It must satisfy the signature: std::complex<double>(
const
std::unordered_map<std::string, std::complex<double>> &).- Parameters:
callable – The callable object to be wrapped and stored for later invocation.
-
scalar_callback(const scalar_callback &other) = default¶
Default copy constructor for scalar_callback. Creates a new scalar_callback instance as a copy of an existing instance.
-
scalar_callback(scalar_callback &&other) = default¶
Move constructor for the scalar_callback class. Transfers ownership from the provided source instance to the new instance.
-
scalar_callback &operator=(const scalar_callback &other) = default¶
Default copy assignment operator for scalar_callback.
-
scalar_callback &operator=(scalar_callback &&other) = default¶
Default move assignment operator for scalar_callback.
-
std::complex<double> operator()(const std::unordered_map<std::string, std::complex<double>> ¶meters) const¶
Evaluates the callback with the provided parameters.
- Parameters:
parameters – A mapping from parameter names to their complex values.
- Returns:
std::complex<double> The computed complex result based on the input parameters.
-
template<typename Callable, std::enable_if_t<std::is_invocable_r_v<std::complex<double>, Callable, const std::unordered_map<std::string, std::complex<double>>&>, bool> = true>
-
class scalar_operator¶
Public Functions
-
bool is_constant() const¶
Checks if the scalar operator represents a constant value.
- Returns:
True if the operator is constant, false otherwise.
-
const std::unordered_map<std::string, std::string> &get_parameter_descriptions() const¶
A map that contains the documentation the parameters of the operator, if available. The operator may use parameters that are not represented in this dictionary.
-
constexpr scalar_operator() = default¶
Default constructor that initializes the scalar operator.
-
scalar_operator(double value)¶
Constructs a scalar operator with a double value.
-
scalar_operator(std::complex<double> value)¶
Constructs a scalar operator with a complex double value.
-
scalar_operator(const scalar_callback &create, std::unordered_map<std::string, std::string> &¶meter_descriptions = {})¶
Constructs a scalar operator from a scalar callback.
-
scalar_operator(scalar_callback &&create, std::unordered_map<std::string, std::string> &¶meter_descriptions = {})¶
Constructs a scalar operator from an rvalue scalar callback.
-
scalar_operator(const scalar_operator &other) = default¶
Copy constructor.
-
scalar_operator(scalar_operator &&other) = default¶
Move constructor.
-
~scalar_operator() = default¶
Default destructor.
-
scalar_operator &operator=(const scalar_operator &other) = default¶
Copy assignment operator.
-
scalar_operator &operator=(scalar_operator &&other) = default¶
Move assignment operator.
-
std::complex<double> evaluate(const std::unordered_map<std::string, std::complex<double>> ¶meters = {}) const¶
Evaluates the scalar operator using the given parameters.
- Parameters:
parameters – A map of parameter names to complex values.
- Returns:
The evaluated complex value.
-
complex_matrix to_matrix(const std::unordered_map<std::string, std::complex<double>> ¶meters = {}) const¶
Converts the scalar operator to a 1x1 matrix.
- Parameters:
parameters – A map of parameter names to complex values.
- Returns:
The 1x1 complex matrix representation.
-
std::string to_string() const¶
Returns a string representation of the scalar operator.
- Returns:
The string representation.
-
bool operator==(const scalar_operator &other) const¶
Compares two scalar operators for equality.
- Parameters:
other – The scalar operator to compare against.
- Returns:
True if both operators are equal, false otherwise.
-
scalar_operator operator-() const &¶
Unary minus operator (lvalue).
- Returns:
A new scalar operator representing the negation.
-
scalar_operator operator-() &&¶
Unary minus operator (rvalue).
- Returns:
A new scalar operator representing the negation.
-
scalar_operator operator+() const &¶
Unary plus operator (lvalue).
- Returns:
A copy of the current scalar operator.
-
scalar_operator operator+() &&¶
Unary plus operator (rvalue).
- Returns:
A moved copy of the current scalar operator.
-
scalar_operator operator*(double other) const &¶
Multiplies the scalar operator by a double (lvalue).
-
scalar_operator operator*(double other) &&¶
Multiplies the scalar operator by a double (rvalue).
-
scalar_operator operator/(double other) const &¶
Divides the scalar operator by a double (lvalue).
-
scalar_operator operator/(double other) &&¶
Divides the scalar operator by a double (rvalue).
-
scalar_operator operator+(double other) const &¶
Adds a double to the scalar operator (lvalue).
-
scalar_operator operator+(double other) &&¶
Adds a double to the scalar operator (rvalue).
-
scalar_operator operator-(double other) const &¶
Subtracts a double from the scalar operator (lvalue).
-
scalar_operator operator-(double other) &&¶
Subtracts a double from the scalar operator (rvalue).
-
scalar_operator &operator*=(double other)¶
Multiplies the scalar operator by a double in-place.
-
scalar_operator &operator/=(double other)¶
Divides the scalar operator by a double in-place.
-
scalar_operator &operator+=(double other)¶
Adds a double to the scalar operator in-place.
-
scalar_operator &operator-=(double other)¶
Subtracts a double from the scalar operator in-place.
-
scalar_operator operator*(std::complex<double> other) const &¶
Multiplies the scalar operator by a complex number (lvalue).
-
scalar_operator operator*(std::complex<double> other) &&¶
Multiplies the scalar operator by a complex number (rvalue).
-
scalar_operator operator/(std::complex<double> other) const &¶
Divides the scalar operator by a complex number (lvalue).
-
scalar_operator operator/(std::complex<double> other) &&¶
Divides the scalar operator by a complex number (rvalue).
-
scalar_operator operator+(std::complex<double> other) const &¶
Adds a complex number to the scalar operator (lvalue).
-
scalar_operator operator+(std::complex<double> other) &&¶
Adds a complex number to the scalar operator (rvalue).
-
scalar_operator operator-(std::complex<double> other) const &¶
Subtracts a complex number from the scalar operator (lvalue).
-
scalar_operator operator-(std::complex<double> other) &&¶
Subtracts a complex number from the scalar operator (rvalue).
-
scalar_operator &operator*=(std::complex<double> other)¶
Multiplies the scalar operator by a complex number in-place.
-
scalar_operator &operator/=(std::complex<double> other)¶
Divides the scalar operator by a complex number in-place.
-
scalar_operator &operator+=(std::complex<double> other)¶
Adds a complex number to the scalar operator in-place.
-
scalar_operator &operator-=(std::complex<double> other)¶
Subtracts a complex number from the scalar operator in-place.
-
scalar_operator operator*(const scalar_operator &other) const &¶
Multiplies two scalar operators (lvalue).
-
scalar_operator operator*(const scalar_operator &other) &&¶
Multiplies two scalar operators (rvalue).
-
scalar_operator operator/(const scalar_operator &other) const &¶
Divides two scalar operators (lvalue).
-
scalar_operator operator/(const scalar_operator &other) &&¶
Divides two scalar operators (rvalue).
-
scalar_operator operator+(const scalar_operator &other) const &¶
Adds two scalar operators (lvalue).
-
scalar_operator operator+(const scalar_operator &other) &&¶
Adds two scalar operators (rvalue).
-
scalar_operator operator-(const scalar_operator &other) const &¶
Subtracts two scalar operators (lvalue).
-
scalar_operator operator-(const scalar_operator &other) &&¶
Subtracts two scalar operators (rvalue).
-
scalar_operator &operator*=(const scalar_operator &other)¶
Multiplies two scalar operators in-place.
-
scalar_operator &operator/=(const scalar_operator &other)¶
Divides two scalar operators in-place.
-
scalar_operator &operator+=(const scalar_operator &other)¶
Adds two scalar operators in-place.
-
scalar_operator &operator-=(const scalar_operator &other)¶
Subtracts two scalar operators in-place.
Friends
-
friend scalar_operator operator*(double other, const scalar_operator &self)¶
Multiplies a double with a scalar operator (lvalue).
-
friend scalar_operator operator*(double other, scalar_operator &&self)¶
Multiplies a double with a scalar operator (rvalue).
-
friend scalar_operator operator/(double other, const scalar_operator &self)¶
Divides a double by a scalar operator (lvalue).
-
friend scalar_operator operator/(double other, scalar_operator &&self)¶
Divides a double by a scalar operator (rvalue).
-
friend scalar_operator operator+(double other, const scalar_operator &self)¶
Adds a double to a scalar operator (lvalue).
-
friend scalar_operator operator+(double other, scalar_operator &&self)¶
Adds a double to a scalar operator (rvalue).
-
friend scalar_operator operator-(double other, const scalar_operator &self)¶
Subtracts a scalar operator from a double (lvalue).
-
friend scalar_operator operator-(double other, scalar_operator &&self)¶
Subtracts a scalar operator from a double (rvalue).
-
friend scalar_operator operator*(std::complex<double> other, const scalar_operator &self)¶
Multiplies a complex number with a scalar operator (lvalue).
-
friend scalar_operator operator*(std::complex<double> other, scalar_operator &&self)¶
Multiplies a complex number with a scalar operator (rvalue).
-
friend scalar_operator operator/(std::complex<double> other, const scalar_operator &self)¶
Divides a complex number by a scalar operator (lvalue).
-
friend scalar_operator operator/(std::complex<double> other, scalar_operator &&self)¶
Divides a complex number by a scalar operator (rvalue).
-
friend scalar_operator operator+(std::complex<double> other, const scalar_operator &self)¶
Adds a complex number to a scalar operator (lvalue).
-
friend scalar_operator operator+(std::complex<double> other, scalar_operator &&self)¶
Adds a complex number to a scalar operator (rvalue).
-
friend scalar_operator operator-(std::complex<double> other, const scalar_operator &self)¶
Subtracts a scalar operator from a complex number (lvalue).
-
friend scalar_operator operator-(std::complex<double> other, scalar_operator &&self)¶
Subtracts a scalar operator from a complex number (rvalue).
-
bool is_constant() const¶
-
struct commutation_relations¶
-
class matrix_callback¶
-
using csr_spmatrix = std::tuple<std::vector<std::complex<double>>, std::vector<std::size_t>, std::vector<std::size_t>>¶
Alias for a tuple containing vectors for complex values, indices, and sizes.
The tuple elements are:
std::vector<std::complex<double>>
: Complex values.std::vector<std::size_t>
: Indices.std::vector<std::size_t>
: Sizes.
-
class operator_handler¶
Subclassed by cudaq::boson_handler, cudaq::fermion_handler, cudaq::matrix_handler, cudaq::spin_handler
-
class spin_handler : public cudaq::operator_handler¶
Public Functions
-
virtual std::string unique_id() const override¶
Generates a unique identifier for the derived class.
- Returns:
A string representing the unique identifier.
-
virtual complex_matrix to_matrix(std::unordered_map<std::size_t, std::int64_t> &dimensions, const std::unordered_map<std::string, std::complex<double>> ¶meters = {}) const override¶
Return the
matrix_handler
as a matrix.dimensions
: A map specifying the number of levels, that is, the dimension of each degree of freedom that the operator acts on. Example for two, 2-level degrees of freedom:{0 : 2, 1 : 2}
.
-
virtual std::string to_string(bool include_degrees) const override¶
Converts the object to a string representation.
- Parameters:
include_degrees – A boolean flag indicating whether to include degrees in the string representation.
- Returns:
A string representation of the object.
Public Static Functions
-
static cudaq::detail::EigenSparseMatrix to_sparse_matrix(const std::string &pauli, std::complex<double> coeff = 1., bool invert_order = false)¶
Computes the sparse matrix representation of a Pauli string. By default, the ordering of the matrix matches the ordering of the Pauli string.
-
static complex_matrix to_matrix(const std::string &pauli, std::complex<double> coeff = 1., bool invert_order = false)¶
Computes the matrix representation of a Pauli string. By default, the ordering of the matrix matches the ordering of the Pauli string.
-
virtual std::string unique_id() const override¶
-
class fermion_handler : public cudaq::operator_handler¶
-
class boson_handler : public cudaq::operator_handler¶
-
class matrix_handler : public cudaq::operator_handler¶
The matrix_handler class manages matrix-based quantum operators. It derives from operator_handler and facilitates the definition, instantiation, evaluation, and manipulation of elementary as well as custom operators that can be represented in matrix form.
Public Functions
-
const std::unordered_map<std::string, std::string> &get_parameter_descriptions() const¶
Returns a map with parameter names and their description if such a map was provided when the operator was defined.
-
const std::vector<std::int64_t> &get_expected_dimensions() const¶
Returns a vector of integers representing the expected dimension for each degree of freedom. A negative value indicates that the operator is defined for any dimension of that degree.
-
virtual std::string unique_id() const override¶
Returns a unique identifier string for this operator instance.
- Returns:
A string representing the unique ID of the operator.
-
virtual std::vector<std::size_t> degrees() const override¶
Returns the degrees of freedom on which the operator acts.
- Returns:
A vector of std::size_t representing the degrees of freedom.
-
matrix_handler(std::size_t target)¶
Constructs a matrix_handler that applies an identity operator to the given target.
- Parameters:
target – A std::size_t representing the target index relevant for the operator.
-
matrix_handler(std::string operator_id, const std::vector<std::size_t> °rees, const commutation_behavior &behavior = commutation_behavior())¶
Instantiates a matrix_handler.
- Parameters:
operator_id – A string identifying the operator definition.
degrees – A vector defining the degrees of freedom that the operator acts on.
behavior – An optional argument to define the commutation behavior.
-
matrix_handler(std::string operator_id, std::vector<std::size_t> &°rees, const commutation_behavior &behavior = commutation_behavior())¶
Instantiates a matrix_handler.
- Parameters:
operator_id – A string identifying the operator definition.
degrees – A vector defining the degrees of freedom that the operator acts on.
behavior – An optional argument to define the commutation behavior.
-
template<typename T, std::enable_if_t<std::is_base_of_v<operator_handler, T>, bool> = true>
matrix_handler(const T &other)¶ Constructs a matrix_handler by copying from an operator_handler-derived instance.
- Template Parameters:
T – A type derived from operator_handler.
- Parameters:
other – A constant reference to the source operator instance.
-
template<typename T, std::enable_if_t<std::is_base_of_v<operator_handler, T>, bool> = true>
matrix_handler(const T &other, const commutation_behavior &behavior)¶ Constructs a matrix_handler from an operator_handler-derived instance with specified commutation behavior.
- Template Parameters:
T – A type derived from operator_handler.
- Parameters:
other – A constant reference to the source operator instance.
behavior – A commutation_behavior object specifying the commutation properties.
-
matrix_handler(const matrix_handler &other)¶
Copy constructs a matrix_handler from another matrix_handler instance.
- Parameters:
other – A constant reference to the other matrix_handler instance.
-
matrix_handler(matrix_handler &&other)¶
Move constructs a matrix_handler by transferring resources from another instance.
- Parameters:
other – An rvalue reference to the other matrix_handler instance.
-
~matrix_handler() = default¶
Default destructor for matrix_handler.
-
matrix_handler &operator=(matrix_handler &&other)¶
Move assigns a matrix_handler instance by transferring resources from another instance.
- Parameters:
other – An rvalue reference to the other matrix_handler instance.
- Returns:
A reference to the assigned matrix_handler.
-
matrix_handler &operator=(const matrix_handler &other)¶
Copy assigns a matrix_handler instance from another matrix_handler.
- Parameters:
other – A constant reference to the other matrix_handler instance.
- Returns:
A reference to the assigned matrix_handler.
-
template<typename T, std::enable_if_t<!std::is_same<T, matrix_handler>::value && std::is_base_of_v<operator_handler, T>, bool> = true>
matrix_handler &operator=(const T &other)¶ Assigns a base operator to a matrix_handler instance.
- Template Parameters:
T – A type derived from operator_handler and not matrix_handler.
- Parameters:
other – A constant reference to the operator_handler-derived instance.
- Returns:
A reference to the assigned matrix_handler.
-
virtual complex_matrix to_matrix(std::unordered_map<std::size_t, std::int64_t> &dimensions, const std::unordered_map<std::string, std::complex<double>> ¶meters = {}) const override¶
Return the
matrix_handler
as a matrix.- Parameters:
`dimensions` – : A map specifying the number of levels, that is, the dimension of each degree of freedom that the operator acts on. Example for two, 2-level degrees of freedom:
{0 : 2, 1 : 2}
.
-
virtual std::string to_string(bool include_degrees) const override¶
Generates a string representation of the matrix_handler.
- Parameters:
include_degrees – A flag indicating whether to include degree information in the string.
- Returns:
A string describing the operator.
-
bool operator==(const matrix_handler &other) const¶
True, if the other value is an elementary operator with the same id acting on the same degrees of freedom, and False otherwise.
Public Static Functions
-
static void define(std::string operator_id, std::vector<std::int64_t> expected_dimensions, matrix_callback &&create, const std::unordered_map<std::string, std::string> ¶meter_descriptions = {})¶
Adds the definition of an elementary operator with the given id to the class. 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. An elementary operator 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:
operator_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. The matrix must be ordered such that the value returned by
op.degrees()
matches the order of the matrix, whereop
is the instantiated the operator defined here. Thecreate
function must take a vector of integers that specifies the “number of levels” (the dimension) for each degree of freedom that the operator acts on, and an unordered map from string to complex double that contains additional parameters the operator may use.
-
static void define(std::string operator_id, std::vector<std::int64_t> expected_dimensions, matrix_callback &&create, std::unordered_map<std::string, std::string> &¶meter_descriptions)¶
Adds the definition of an elementary operator with the given id to the class. 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. An elementary operator 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:
operator_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. The matrix must be ordered such that the value returned by
op.degrees()
matches the order of the matrix, whereop
is the instantiated the operator defined here. Thecreate
function must take a vector of integers that specifies the “number of levels” (the dimension) for each degree of freedom that the operator acts on, and an unordered map from string to complex double that contains additional parameters the operator may use.
-
static bool remove_definition(const std::string &operator_id)¶
Removes any definition for an operator with the given id. Returns true if the definition was removed, returns false if no definition of an operator with the given id existed in the first place.
-
static product_op<matrix_handler> instantiate(std::string operator_id, const std::vector<std::size_t> °rees, const commutation_behavior &behavior = commutation_behavior())¶
Instantiates a custom operator.
- Parameters:
operator_id – : The ID of the operator as specified when it was defined.
degrees – : the degrees of freedom that the operator acts upon.
-
static product_op<matrix_handler> instantiate(std::string operator_id, std::vector<std::size_t> &°rees, const commutation_behavior &behavior = commutation_behavior())¶
Instantiates a custom operator.
- Parameters:
operator_id – : The ID of the operator as specified when it was defined.
degrees – : the degrees of freedom that the operator acts upon.
-
static matrix_handler number(std::size_t degree)¶
Constructs a operator representing a number operator for the given degree.
- Parameters:
degree – : The degree of freedom that the parity operator acts on.
- Returns:
A matrix_handler instance that encapsulates the constructed number operator matrix.
-
static matrix_handler parity(std::size_t degree)¶
Creates a parity operator with matrix_handler.
- Parameters:
degree – : The degree of freedom that the parity operator acts on.
- Returns:
A matrix_handler that encapsulates the parity transformation.
-
static matrix_handler position(std::size_t degree)¶
Constructs a position operator representing the position operator.
- Parameters:
degree – : The degree of freedom that the parity operator acts on.
- Returns:
A matrix_handler that embodies the position operator.
-
static matrix_handler momentum(std::size_t degree)¶
Constructs a momentum operator based on the specified degree.
- Parameters:
degree – : The degree of freedom that the parity operator acts on.
- Returns:
A matrix_handler that represents the momentum operator.
-
static matrix_handler squeeze(std::size_t degree)¶
Creates a squeeze operator with a specific degree.
- Parameters:
degree – : The degree of freedom that the parity operator acts on.
- Returns:
A matrix_handler representing the squeeze transformation.
-
static matrix_handler displace(std::size_t degree)¶
Creates a displacement operator based on a specified degree.
- Parameters:
degree – : The degree of freedom that the parity operator acts on.
- Returns:
A matrix handler representing the displacement.
-
struct commutation_behavior¶
The commutation_behavior struct encapsulates the commutation properties for a matrix operator:
group: Specifies the commutation relations group (using commutation_relations enum), defaulting to the operator_handler’s default_commutation_relations.
commutes_across_degrees: A flag indicating whether the operator commutes across different degrees of freedom.
-
const std::unordered_map<std::string, std::string> &get_parameter_descriptions() const¶
-
template<typename HandlerTy>
class product_op¶ Represents an operator expression consisting of a product of elementary and scalar operators. Operator expressions cannot be used within quantum kernels, but they provide methods to convert them to data types that can.
Public Functions
-
inline const_iterator begin() const¶
Get iterator to beginning of operator terms.
-
inline const_iterator end() const¶
Get iterator to end of operator terms.
-
std::vector<std::size_t> degrees() const¶
The degrees of freedom that the operator acts on. 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.}.
-
std::size_t num_ops() const¶
Return the number of operator terms that make up this product operator.
-
std::string get_term_id() const¶
The term id uniquely identifies the operators and targets (degrees) that they act on, but does not include information about the coefficient.
-
scalar_operator get_coefficient() const¶
Retrieves the coefficient associated with this operator instance.
- Returns:
A scalar_operator representing the operator’s coefficient.
-
inline constexpr product_op()¶
Default constructor for the product_op class.
-
inline constexpr product_op(std::size_t first_degree, std::size_t last_degree)¶
Constructor instantiates a product that applies an identity operator to all targets in the open range [first_degree, last_degree).
-
product_op(double coefficient)¶
Constructs a product operator with the given coefficient.
- Parameters:
coefficient – A double representing the scaling factor for the product operator.
-
product_op(std::complex<double> coefficient)¶
Constructs a product operator with the given coefficient.
- Parameters:
coefficient – A complex of double representing the scaling factor for the product operator.
-
product_op(HandlerTy &&atomic)¶
Constructs a product operator from a given atomic operator handler.
- Template Parameters:
HandlerTy – The type of the underlying atomic operator handler.
- Parameters:
atomic – An rvalue reference to the atomic operator handler.
-
template<typename T, std::enable_if_t<!std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
product_op(const product_op<T> &other)¶ Constructs a product_op from another product_op instance. This constructor is enabled only if T is not equivalent to HandlerTy and if HandlerTy can be constructed from T. It allows implicit conversion between different instantiations of product_op.
- Parameters:
other – The product_op instance to copy from.
-
template<typename T, std::enable_if_t<std::is_same<HandlerTy, matrix_handler>::value && !std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
product_op(const product_op<T> &other, const matrix_handler::commutation_behavior &behavior)¶ Constructs a product operator from an existing product operator with a different type. This constructor enables the creation of a new product_op object when the HandlerTy is a matrix_handler, provided that the type T is not the same as HandlerTy but is convertible to HandlerTy. It allows for proper handling of commutation behavior during the construction.
- Template Parameters:
T – The type of the operand from which the new product_op is constructed.
- Parameters:
other – The source product_op instance from which to create this new object.
behavior – The commutation behavior to be used with the matrix_handler.
-
product_op(const product_op<HandlerTy> &other, std::size_t size = 0)¶
Constructs a new product_op by copying an existing product_op instance.
- Parameters:
other – The product_op instance to be copied.
size – An optional parameter to specify how many operator elements to reserve space for.
-
product_op(product_op<HandlerTy> &&other, std::size_t size = 0)¶
Constructs a product_op by moving the resources from an existing product_op instance.
- Parameters:
other – An rvalue reference to the product_op to move from.
size – An optional size parameter indicating how many operator elements to reserve space for. to adjust or specify internal dimensions.
-
~product_op() = default¶
Default destructor for product_op.
The explicit default destructor allowing the compiler for proper resource cleanup.
-
template<typename T, std::enable_if_t<!std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
product_op<HandlerTy> &operator=(const product_op<T> &other)¶ Templated assignment operator that enables assigning from a product_op with a different but convertible type. This operator is only enabled when the template parameter T is not the same as HandlerTy and is constructible as a HandlerTy. It allows for copying or converting a product_op instance of type T into one of type HandlerTy.
- Template Parameters:
T – The type of the product_op to be assigned from, which must satisfy that it is not HandlerTy and is constructible as HandlerTy.
-
product_op<HandlerTy> &operator=(const product_op<HandlerTy> &other) = default¶
Assignment operator for the product_op class.
- Parameters:
other – The product_op instance to be assigned.
- Returns:
A reference to the assigned product_op instance.
-
product_op<HandlerTy> &operator=(product_op<HandlerTy> &&other) = default¶
Move assignment operator for product_op.
- Parameters:
other – The product_op instance to move from.
- Returns:
A reference to the assigned product_op instance.
-
complex_matrix to_matrix(std::unordered_map<std::size_t, std::int64_t> dimensions = {}, const std::unordered_map<std::string, std::complex<double>> ¶meters = {}, bool invert_order = false) const¶
Return the matrix representation of the operator. By default, the matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by default by
degrees
.- Parameters:
`dimensions` – : A mapping that specifies the number of levels, that is, the dimension of each degree of freedom that the operator acts on. Example for two, 2-level degrees of freedom:
{0:2, 1:2}
.`parameters` – : A map of the parameter names to their concrete, complex values.
invert_order
: if set to true, the ordering convention is reversed.
-
bool operator==(const product_op<HandlerTy> &other) const¶
True, if the other value is an sum_op<HandlerTy> with equivalent terms, and False otherwise. The equality takes into account that operator addition is commutative, as is the product of two operators if they act on different degrees of freedom. The equality comparison does not take commutation relations into account, and does not try to reorder terms
blockwise
; it may hence evaluate to False, even if two operators in reality are the same. If the equality evaluates to True, on the other hand, the operators are guaranteed to represent the same transformation for all arguments.
-
product_op<HandlerTy> operator-() const &¶
Unary negation operator for the product_op class.
- Returns:
A new product_op object with the negated value.
-
product_op<HandlerTy> operator-() &&¶
Unary negation operator for product_op.
- Returns:
A new product_op object with the negated value.
-
product_op<HandlerTy> operator+() const &¶
Unary plus operator for the product_op class.
- Returns:
A new product_op object.
-
product_op<HandlerTy> operator+() &&¶
Overloaded unary plus operator for product_op.
- Returns:
A product_op object with the current handler type.
-
product_op<HandlerTy> operator*(scalar_operator &&other) const &¶
Overloaded multiplication operator for combining a scalar operator with a product operator.
- Parameters:
other – The scalar operator to be multiplied.
- Returns:
A new product operator resulting from the multiplication.
-
product_op<HandlerTy> operator*(scalar_operator &&other) &&¶
Multiplies the current operator with a scalar operator to yield a product operator.
- Parameters:
other – An rvalue reference to the scalar_operator that is multiplied with the current operator.
- Returns:
A product_op containing the resulting operator after multiplication.
-
product_op<HandlerTy> operator*(const scalar_operator &other) const &¶
Multiplies this operator with a scalar operator, yielding a product operator.
- Parameters:
other – The scalar operator to multiply with.
- Returns:
A product_op representing the product of the current operator and the provided scalar_operator.
-
product_op<HandlerTy> operator*(const scalar_operator &other) &&¶
Multiplies the current operator (as an rvalue) with a scalar operator.
- Parameters:
other – The scalar operator to multiply with.
- Returns:
A product_op<HandlerTy> representing the product of the multiplication.
-
product_op<HandlerTy> operator/(scalar_operator &&other) const &¶
Divides the current operator by a scalar operator.
- Parameters:
other – A scalar operator to be divided from the current operator.
- Returns:
A product operator representing the result of the division operation.
-
product_op<HandlerTy> operator/(scalar_operator &&other) &&¶
Divides the current rvalue operator by a scalar operator.
- Parameters:
other – An rvalue reference to the scalar operator to be used in the division.
- Returns:
A product_op representing the result of the division.
-
product_op<HandlerTy> operator/(const scalar_operator &other) const &¶
Divides this operator by a scalar operator, yielding a product operator.
- Parameters:
other – The scalar operator used as the divisor.
- Returns:
A product_op representing the result of the division.
-
product_op<HandlerTy> operator/(const scalar_operator &other) &&¶
Divides an rvalue product operator by a scalar operator.
- Parameters:
other – The scalar operator by which the product operator is divided.
- Returns:
A new product operator representing the result of the division.
-
sum_op<HandlerTy> operator+(scalar_operator &&other) const &¶
Adds a scalar operator to the current operator, yielding a new aggregated sum operator.
- Parameters:
other – An rvalue reference to a scalar operator which is to be added.
- Returns:
A new sum_op instance representing the combined effect of the current operator and the provided scalar operator.
-
sum_op<HandlerTy> operator+(scalar_operator &&other) &&¶
Combines the current operator with a provided scalar operator.
- Parameters:
other – An rvalue reference to a scalar_operator to be added.
- Returns:
A sum_op<HandlerTy> representing the resulting sum of the operators.
-
sum_op<HandlerTy> operator+(const scalar_operator &other) const &¶
Adds the current scalar_operator with the given scalar_operator, yielding a new sum_op instance that encapsulates the resulting operation.
- Parameters:
other – The scalar_operator instance to be added.
- Returns:
A sum_op instance representing the sum of the two operators.
-
sum_op<HandlerTy> operator+(const scalar_operator &other) &&¶
Overloads the binary + operator to add a scalar operator to a temporary operator instance.
- Parameters:
other – The scalar_operator instance to be added.
- Returns:
A sum_op object representing the combined operator after performing the addition.
-
sum_op<HandlerTy> operator-(scalar_operator &&other) const &¶
Subtracts a scalar operator from this instance (l-value reference).
- Parameters:
other – R-value reference to scalar_operator.
- Returns:
A sum_op instance representing the subtraction.
-
sum_op<HandlerTy> operator-(scalar_operator &&other) &&¶
Subtracts a scalar operator from this instance (r-value reference).
- Parameters:
other – R-value reference to scalar_operator.
- Returns:
A sum_op instance representing the subtraction.
-
sum_op<HandlerTy> operator-(const scalar_operator &other) const &¶
Subtracts a scalar operator (by
const
reference) from this instance (l-value reference).- Parameters:
other – Constant reference to scalar_operator.
- Returns:
A sum_op instance representing the subtraction.
-
sum_op<HandlerTy> operator-(const scalar_operator &other) &&¶
Subtracts a scalar operator (by
const
reference) from this instance (r-value reference).- Parameters:
other – Constant reference to scalar_operator.
- Returns:
A sum_op instance representing the subtraction.
-
product_op<HandlerTy> operator*(const product_op<HandlerTy> &other) const &¶
Multiplies this instance (l-value reference) by another product_op instance.
- Parameters:
other – Constant reference to another product_op.
- Returns:
A product_op representing the multiplication.
-
product_op<HandlerTy> operator*(const product_op<HandlerTy> &other) &&¶
Multiplies this instance (r-value reference) by another product_op instance.
- Parameters:
other – Constant reference to another product_op.
- Returns:
A product_op representing the multiplication.
-
product_op<HandlerTy> operator*(product_op<HandlerTy> &&other) const &¶
Multiplies this instance (l-value reference) by another product_op instance (r-value).
- Parameters:
other – R-value reference to another product_op.
- Returns:
A product_op representing the multiplication.
-
product_op<HandlerTy> operator*(product_op<HandlerTy> &&other) &&¶
Multiplies this instance (r-value reference) by another product_op instance (r-value).
- Parameters:
other – R-value reference to another product_op.
- Returns:
A product_op representing the multiplication.
-
sum_op<HandlerTy> operator+(const product_op<HandlerTy> &other) const &¶
Adds a product_op (l-value) to this instance (l-value).
- Parameters:
other – Constant reference to product_op.
- Returns:
A sum_op representing the addition.
-
sum_op<HandlerTy> operator+(const product_op<HandlerTy> &other) &&¶
Adds a product_op (l-value) to this instance (r-value).
- Parameters:
other – Constant reference to product_op.
- Returns:
A sum_op representing the addition.
-
sum_op<HandlerTy> operator+(product_op<HandlerTy> &&other) const &¶
Adds a product_op (r-value) to this instance (l-value).
- Parameters:
other – R-value reference to product_op.
- Returns:
A sum_op representing the addition.
-
sum_op<HandlerTy> operator+(product_op<HandlerTy> &&other) &&¶
Adds a product_op (r-value) to this instance (r-value).
- Parameters:
other – R-value reference to product_op.
- Returns:
A sum_op representing the addition.
-
sum_op<HandlerTy> operator-(const product_op<HandlerTy> &other) const &¶
Subtracts a product_op (l-value) from this instance (l-value).
- Parameters:
other – Constant reference to product_op.
- Returns:
A sum_op representing the subtraction.
-
sum_op<HandlerTy> operator-(const product_op<HandlerTy> &other) &&¶
Subtracts a product_op (l-value) from this instance (r-value).
- Parameters:
other – Constant reference to product_op.
- Returns:
A sum_op representing the subtraction.
-
sum_op<HandlerTy> operator-(product_op<HandlerTy> &&other) const &¶
Subtracts a product_op (r-value) from this instance (l-value).
- Parameters:
other – R-value reference to product_op.
- Returns:
A sum_op representing the subtraction.
-
sum_op<HandlerTy> operator-(product_op<HandlerTy> &&other) &&¶
Subtracts a product_op (r-value) from this instance (r-value).
- Parameters:
other – R-value reference to product_op.
- Returns:
A sum_op representing the subtraction.
-
sum_op<HandlerTy> operator+(const sum_op<HandlerTy> &other) const &¶
Adds a sum_op (l-value) to this instance (l-value).
-
sum_op<HandlerTy> operator+(const sum_op<HandlerTy> &other) &&¶
Adds a sum_op (l-value) to this instance (r-value).
-
sum_op<HandlerTy> operator+(sum_op<HandlerTy> &&other) const &¶
Adds a sum_op (r-value) to this instance (l-value).
-
sum_op<HandlerTy> operator+(sum_op<HandlerTy> &&other) &&¶
Adds a sum_op (r-value) to this instance (r-value).
-
sum_op<HandlerTy> operator-(const sum_op<HandlerTy> &other) const &¶
Subtracts a sum_op (l-value) from this instance (l-value).
-
sum_op<HandlerTy> operator-(const sum_op<HandlerTy> &other) &&¶
Subtracts a sum_op (l-value) from this instance (r-value).
-
sum_op<HandlerTy> operator-(sum_op<HandlerTy> &&other) const &¶
Subtracts another sum_op object from this one.
-
product_op<HandlerTy> &operator*=(const scalar_operator &other)¶
Multiplies the current product operator by a scalar operator.
- Parameters:
other – The scalar operator to multiply with.
- Returns:
A reference to the modified product operator.
-
product_op<HandlerTy> &operator/=(const scalar_operator &other)¶
Overloads the division assignment operator to divide the current product operator by a scalar operator.
- Parameters:
other – The scalar operator to divide by.
- Returns:
A reference to the modified product operator.
-
product_op<HandlerTy> &operator*=(const product_op<HandlerTy> &other)¶
Compound assignment operator that multiplies this product_op with another product_op.
- Parameters:
other – The product_op to multiply with.
- Returns:
A reference to the modified product_op.
-
product_op<HandlerTy> &operator*=(product_op<HandlerTy> &&other)¶
Multiplies this product operator with another product operator and assigns the result to this operator.
- Parameters:
other – The product operator to multiply with.
- Returns:
A reference to the modified product operator.
-
bool is_identity() const¶
Checks if all operators in the product are the identity. Note: this function returns true regardless of the value of the coefficient.
-
std::string to_string() const¶
Return the string representation of the operator.
-
void dump() const¶
Print the string representation of the operator to the standard output.
-
product_op<HandlerTy> &canonicalize()¶
Removes all identity operators from the operator.
-
product_op<HandlerTy> &canonicalize(const std::set<std::size_t> °rees)¶
Expands the operator to act on all given degrees, applying identities as needed.
-
csr_spmatrix to_sparse_matrix(std::unordered_map<std::size_t, std::int64_t> dimensions = {}, const std::unordered_map<std::string, std::complex<double>> ¶meters = {}, bool invert_order = false) const¶
Return the matrix representation of the operator. By default, the matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees
. See the documentation fordegrees
for more detail.dimensions
: A mapping that specifies the number of levels, that is, the dimension of each degree of freedom that the operator acts on. Example for two, 2-level degrees of freedom:{0:2, 1:2}
.parameters
: A map of the parameter names to their concrete, complex values.invert_order
: if set to true, the ordering convention is reversed.
Friends
-
template<typename T>
friend product_op<T> operator*(scalar_operator &&other, const product_op<T> &self)¶ Overloads the multiplication operator to multiply a scalar operator with a product operator. This function enables left-sided multiplication of a scalar operator (provided as an rvalue reference) with an existing product operator, producing a new product operator that encapsulates the resultant state.
- Template Parameters:
T – The type parameter used within the product operator.
- Parameters:
other – The scalar operator to be multiplied (rvalue reference).
self – The product operator to be multiplied.
- Returns:
A new product operator that is the result of multiplying the scalar operator with the product operator.
-
template<typename T>
friend product_op<T> operator*(scalar_operator &&other, product_op<T> &&self)¶ Overloads the multiplication operator to multiply a scalar_operator with a product_op.
- Template Parameters:
T – The type of the elements in the product_op.
- Parameters:
other – The scalar_operator to be multiplied.
self – The product_op to be multiplied.
- Returns:
A new product_op resulting from the multiplication of the scalar_operator and the product_op.
-
template<typename T>
friend product_op<T> operator*(const scalar_operator &other, const product_op<T> &self)¶ Overloads the multiplication operator to allow multiplication between a scalar_operator and a product_op<T>.
- Parameters:
other – The scalar_operator to be multiplied.
self – The product_op<T> to be multiplied.
- Returns:
A new product_op<T> resulting from the multiplication of the scalar_operator and the product_op<T>.
-
template<typename T>
friend product_op<T> operator*(const scalar_operator &other, product_op<T> &&self)¶ Overloaded multiplication operator for combining a scalar operator with a product operator.
- Parameters:
other – The scalar operator to be multiplied.
self – The product operator to be multiplied, passed as an rvalue reference.
- Returns:
A new product operator resulting from the multiplication of the scalar operator and the product operator.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, const product_op<T> &self)¶ Overloads the addition operator to add a scalar_operator to a product_op.
- Parameters:
other – The scalar_operator to be added.
self – The product_op to which the scalar_operator is added.
- Returns:
A sum_op object representing the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, product_op<T> &&self)¶ Overloads the addition operator to add a scalar_operator and a product_op.
- Parameters:
other – The scalar_operator to be added.
self – The product_op to be added.
- Returns:
A sum_op object representing the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, const product_op<T> &self)¶ Overloads the addition operator to combine a scalar operator with a product operator.
- Parameters:
other – The scalar operator to be added.
self – The product operator to be added.
- Returns:
A sum operator representing the combined result of the scalar and product operators.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, product_op<T> &&self)¶ Overloads the + operator to add a scalar_operator to a product_op.
- Template Parameters:
T – The type of the elements in the product_op.
- Parameters:
other – The scalar_operator to be added.
self – The product_op to which the scalar_operator is added.
- Returns:
A sum_op<T> representing the result of the addition.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, const product_op<T> &self)¶ Overloads the subtraction operator to subtract a product_op object from a scalar_operator object.
- Template Parameters:
T – The type of the elements in the product_op.
- Parameters:
other – The scalar_operator object to be subtracted from.
self – The product_op object to subtract.
- Returns:
A sum_op object representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, product_op<T> &&self)¶ Overloads the subtraction operator for a scalar_operator and a product_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The product_op from which the scalar_operator is subtracted.
- Returns:
A sum_op<T> representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(const scalar_operator &other, const product_op<T> &self)¶ Overloads the subtraction operator to subtract a product operator from a scalar operator.
- Parameters:
other – The scalar operator to subtract from.
self – The product operator to be subtracted.
- Returns:
A sum_op object representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(const scalar_operator &other, product_op<T> &&self)¶ Overloads the subtraction operator to subtract a scalar_operator from a product_op.
- Template Parameters:
T – The type of the elements in the product_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The product_op from which the scalar_operator is subtracted.
- Returns:
A sum_op<T> representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator*(scalar_operator &&other, const sum_op<T> &self)¶ Overloaded multiplication operator for scalar_operator and sum_op.
- Parameters:
other – The scalar_operator to be multiplied.
self – The sum_op to be multiplied.
- Returns:
A new sum_op resulting from the multiplication of the scalar_operator and the sum_op.
-
template<typename T>
friend sum_op<T> operator*(scalar_operator &&other, sum_op<T> &&self)¶ Overloaded multiplication operator for combining a scalar operator with a sum operator.
- Parameters:
other – The scalar operator to be multiplied.
self – The sum operator to be multiplied.
- Returns:
A new sum_op<T> resulting from the multiplication of the scalar operator and the sum operator.
-
template<typename T>
friend sum_op<T> operator*(const scalar_operator &other, const sum_op<T> &self)¶ Overloads the multiplication operator to allow multiplication of a scalar_operator with a sum_op.
- Parameters:
other – The scalar_operator to be multiplied.
self – The sum_op to be multiplied.
- Returns:
A new sum_op resulting from the multiplication of the scalar_operator and the sum_op.
-
template<typename T>
friend sum_op<T> operator*(const scalar_operator &other, sum_op<T> &&self)¶ Multiplies a scalar_operator with a sum_op object.
- Parameters:
other – The scalar_operator to multiply.
self – The sum_op object to be multiplied.
- Returns:
A new sum_op object that is the result of the multiplication.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, const sum_op<T> &self)¶ Overloads the addition operator to add a scalar_operator to a sum_op object.
- Parameters:
other – The scalar_operator object to be added.
self – The sum_op object to which the scalar_operator is added.
- Returns:
A new sum_op object that represents the sum of the scalar_operator and the sum_op.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, sum_op<T> &&self)¶ Overloads the addition operator for combining a scalar_operator and a sum_op.
- Template Parameters:
T – The type of the elements in the sum_op.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op to which the scalar_operator will be added.
- Returns:
A new sum_op<T> that is the result of adding the scalar_operator to the sum_op.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, const sum_op<T> &self)¶ Overloads the addition operator to allow adding a scalar_operator to a sum_op object.
- Template Parameters:
T – The type of the elements in the sum_op.
- Parameters:
other – The scalar_operator object to be added.
self – The sum_op object to which the scalar_operator is added.
- Returns:
A new sum_op object that is the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, sum_op<T> &&self)¶ Overloads the addition operator to add a scalar_operator to a sum_op.
- Template Parameters:
T – The type of the elements in the sum_op.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op to which the scalar_operator is added.
- Returns:
A new sum_op that is the result of the addition.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, const sum_op<T> &self)¶ Subtracts a sum_op object from a scalar_operator object.
- Parameters:
other – The scalar_operator object to be subtracted.
self – The sum_op object from which the scalar_operator is subtracted.
- Returns:
A new sum_op object representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, sum_op<T> &&self)¶ Overloads the subtraction operator for a scalar_operator and a sum_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The sum_op from which the scalar_operator is subtracted.
- Returns:
A new sum_op resulting from the subtraction.
-
template<typename T>
friend sum_op<T> operator-(const scalar_operator &other, const sum_op<T> &self)¶ Overloads the subtraction operator to subtract a scalar_operator from a sum_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The sum_op from which the scalar_operator is subtracted.
- Returns:
A new sum_op representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(const scalar_operator &other, sum_op<T> &&self)¶ Overloads the subtraction operator for scalar_operator and sum_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The sum_op object from which the scalar_operator is subtracted.
- Returns:
A new sum_op object resulting from the subtraction.
-
struct const_iterator¶
Public Functions
-
inline const_iterator(const product_op<HandlerTy> *prod, std::size_t idx = 0)¶
Constructs a const_iterator for a given product operator.
- Parameters:
prod – Pointer to the product operator containing the operators.
idx – Starting index for the iterator (default is 0).
-
inline bool operator==(const const_iterator &other) const¶
Compares this iterator with another for equality.
- Parameters:
other – Another const_iterator to compare with.
- Returns:
True if both iterators refer to the same product operator and current index, false otherwise.
-
inline bool operator!=(const const_iterator &other) const¶
Compares this iterator with another for inequality.
- Parameters:
other – Another const_iterator to compare with.
- Returns:
True if the iterators do not refer to the same product operator or index.
-
inline const HandlerTy &operator*() const¶
Dereferences
the iterator to access the current operator.- Returns:
A constant reference to the current operator.
-
inline const HandlerTy *operator->()¶
Provides pointer-like access to the current operator.
- Returns:
A pointer to the current operator.
-
inline const_iterator &operator++()¶
Advances the iterator to the next operator (prefix increment).
- Returns:
Reference to the updated iterator.
-
inline const_iterator &operator--()¶
Moves the iterator to the previous operator (prefix decrement).
- Returns:
Reference to the updated iterator.
-
inline const_iterator operator++(int)¶
Advances the iterator (
postfix
increment) and returns the iterator state before increment.- Returns:
A const_iterator representing the state prior to increment.
-
inline const_iterator operator--(int)¶
Moves the iterator (
postfix
decrement) and returns the iterator state before decrement.- Returns:
A const_iterator representing the state prior to decrement.
-
inline const_iterator(const product_op<HandlerTy> *prod, std::size_t idx = 0)¶
-
inline const_iterator begin() const¶
-
template<typename HandlerTy>
class sum_op¶ Represents a sum of operator products in a quantum operator algebra.
The sum_op class is a templated container that encapsulates a linear combination of product operators, where each term is defined by a specific configuration of operator components paired with a scalar coefficient.
Public Functions
-
inline const_iterator begin() const¶
Get iterator to beginning of operator terms.
-
inline const_iterator end() const¶
Get iterator to end of operator terms.
-
std::vector<std::size_t> degrees() const¶
The degrees of freedom that the operator acts on. The order of degrees is from smallest to largest and reflect 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.}.
-
std::size_t num_terms() const¶
Return the number of operator terms that make up this operator sum.
-
template<typename ...Args, std::enable_if_t<std::conjunction<std::is_same<product_op<HandlerTy>, Args>...>::value && sizeof...(Args), bool> = true>
sum_op(Args&&... args)¶ Constructs a new sum operator instance from product operator arguments.
- Template Parameters:
`Args` – Variadic template parameters representing product_op<HandlerTy> types.
- Parameters:
args – One or more product operator objects used in the summation operation.
-
sum_op(const product_op<HandlerTy> &other)¶
Constructs a sum_op instance from a given product_op instance.
- Parameters:
other – A reference to the product_op object used to construct this sum_op.
-
template<typename T, std::enable_if_t<!std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
sum_op(const sum_op<T> &other)¶ Copy constructor for sum_op that enables conversion from a sum_op instantiated with a different type.
- Template Parameters:
T – The type of the other sum_op object, which must not be HandlerTy and must be constructible to HandlerTy.
-
template<typename T, std::enable_if_t<std::is_same<HandlerTy, matrix_handler>::value && !std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
sum_op(const sum_op<T> &other, const matrix_handler::commutation_behavior &behavior)¶ Constructs a new sum_op object from an existing sum_op of a different, constructible type.
- Parameters:
other – The source sum_op object whose contents are used for construction.
behavior – The commutation behavior to be applied during construction.
-
~sum_op() = default¶
Default destructor.
-
template<typename T, std::enable_if_t<!std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
sum_op<HandlerTy> &operator=(const product_op<T> &other)¶ Assigns a product_op to a sum_op. This operator overload enables assignment from a product_op<T> to a sum_op<HandlerTy>. It is only enabled when T is not the same as HandlerTy and when HandlerTy is constructible from T. This constraint ensures that only compatible types are allowed in the assignment operation.
-
sum_op<HandlerTy> &operator=(const product_op<HandlerTy> &other)¶
Assign a product_op object to a sum_op object.
- Parameters:
other – A constant reference to the product_op object to be assigned.
- Returns:
A reference to the sum_op object after the assignment.
-
sum_op<HandlerTy> &operator=(product_op<HandlerTy> &&other)¶
Assigns the contents of a product operation to the current sum operation using move semantics.
- Parameters:
other – An rvalue reference to a product_op instance whose resources will be transferred.
- Returns:
A reference to the updated sum_op instance.
-
template<typename T, std::enable_if_t<!std::is_same<T, HandlerTy>::value && std::is_constructible<HandlerTy, T>::value, bool> = true>
sum_op<HandlerTy> &operator=(const sum_op<T> &other)¶ Template assignment operator allowing conversion between different sum_op types.
-
sum_op<HandlerTy> &operator=(const sum_op<HandlerTy> &other) = default¶
Performs a copy assignment of one sum_op to another.
-
complex_matrix to_matrix(std::unordered_map<std::size_t, std::int64_t> dimensions = {}, const std::unordered_map<std::string, std::complex<double>> ¶meters = {}, bool invert_order = false) const¶
Return the matrix representation of the operator. By default, the matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by default by
degrees
.- Parameters:
`dimensions` – : A mapping that specifies the number of levels, that is, the dimension of each degree of freedom that the operator acts on. Example for two, 2-level degrees of freedom:
{0:2, 1:2}
.`parameters` – : A map of the parameter names to their concrete, complex values.
invert_order
: if set to true, the ordering convention is reversed.
-
bool operator==(const sum_op<HandlerTy> &other) const¶
True, if the other value is an sum_op<HandlerTy> with equivalent terms, and False otherwise. The equality takes into account that operator addition is commutative, as is the product of two operators if they act on different degrees of freedom. The equality comparison does not take commutation relations into account, and does not try to reorder terms
blockwise
; it may hence evaluate to False, even if two operators in reality are the same. If the equality evaluates to True, on the other hand, the operators are guaranteed to represent the same transformation for all arguments.
-
sum_op<HandlerTy> operator-() const &¶
Returns a new sum_op instance representing the negation of this object.
-
sum_op<HandlerTy> operator-() &&¶
Applies the unary negation to a sum_op object using move semantics.
-
sum_op<HandlerTy> operator+() const &¶
Returns a new sum_op instance using the unary plus operator.
- Returns:
A new instance of sum_op<HandlerTy> representing the unary plus operation.
-
sum_op<HandlerTy> operator*(const scalar_operator &other) const &¶
Multiplies the current operator with a scalar operator.
- Parameters:
other – The scalar_operator to multiply with.
- Returns:
A new sum_op instance encapsulating the result of the multiplication.
-
sum_op<HandlerTy> operator*(const scalar_operator &other) &&¶
Overloads the multiplication operator to combine a rvalue sum operator with a scalar operator.
- Parameters:
other – A constant reference to a scalar_operator that will be multiplied with the current rvalue sum operator.
- Returns:
A new sum_op<HandlerTy> representing the resulting operator after applying the multiplication.
-
sum_op<HandlerTy> operator/(const scalar_operator &other) const &¶
Performs division of the current sum operator by a scalar operator.
- Parameters:
other – The scalar operator serving as the divisor.
- Returns:
A new sum operator resulting from the division operation.
-
sum_op<HandlerTy> operator/(const scalar_operator &other) &&¶
Overloaded division operator for a rvalue instance of the operator.
- Parameters:
other – The scalar_operator divisor used in the division.
- Returns:
A sum_op representing the result of the division operation.
-
sum_op<HandlerTy> operator+(scalar_operator &&other) const &¶
Combines the current operator with a scalar operator to form a new sum operator.
- Parameters:
other – The scalar operator to be incorporated into the sum.
- Returns:
A sum_op instance representing the combined operator.
-
sum_op<HandlerTy> operator+(scalar_operator &&other) &&¶
Combines the current sum_op with an additional scalar_operator.
- Parameters:
other – An rvalue reference to a scalar_operator to be added.
- Returns:
A new sum_op representing the sum of the current operator and the provided scalar_operator.
-
sum_op<HandlerTy> operator+(const scalar_operator &other) const &¶
Overloads the addition operator to combine the current sum operator with a scalar operator.
- Parameters:
other – The scalar_operator instance to be added to the sum operator.
- Returns:
A sum_op<HandlerTy> representing the result of combining the current operator with the specified scalar operator.
-
sum_op<HandlerTy> operator+(const scalar_operator &other) &&¶
Adds a scalar operator to the current operator instance.
- Parameters:
other – The scalar operator to be added to this operator.
- Returns:
A new sum_op<HandlerTy> representing the sum of the current operator and the provided scalar operator.
-
sum_op<HandlerTy> operator-(scalar_operator &&other) const &¶
Subtracts a scalar operator from the current operator instance.
- Parameters:
other – An rvalue reference to a scalar_operator that will be subtracted from the current instance.
- Returns:
A sum_op<HandlerTy> object that represents the result of the subtraction.
-
sum_op<HandlerTy> operator-(scalar_operator &&other) &&¶
Overloads the subtraction operator to subtract a scalar_operator from an rvalue instance.
- Parameters:
other – A rvalue reference to a scalar_operator object to subtract.
- Returns:
A sum_op object representing the result of the subtraction.
-
sum_op<HandlerTy> operator-(const scalar_operator &other) const &¶
Subtracts a scalar operator from the current operator.
- Parameters:
other – The scalar_operator instance to subtract.
- Returns:
A new sum_op object representing the result of the subtraction.
-
sum_op<HandlerTy> operator-(const scalar_operator &other) &&¶
Subtract a scalar operator from the current operator (rvalue context).
- Parameters:
other – The scalar operator to subtract.
- Returns:
sum_op<HandlerTy> The resultant operator after performing the subtraction.
-
sum_op<HandlerTy> operator*(const product_op<HandlerTy> &other) const¶
Multiplies this operator with a product operator, yielding a sum operator.
- Parameters:
other – The product operator to be multiplied with this operator.
- Returns:
A sum operator that represents the result of the multiplication.
-
sum_op<HandlerTy> operator+(const product_op<HandlerTy> &other) const &¶
Adds a product operation to the current sum operation.
- Parameters:
other – A
const
reference to the product operation to be added.- Returns:
A new sum operation that encapsulates the result of the addition.
-
sum_op<HandlerTy> operator+(const product_op<HandlerTy> &other) &&¶
Constructs a sum operation by adding a product operation to the current rvalue product operation.
- Parameters:
other – A constant reference to a product_op instance to be added.
- Returns:
A sum_op instance representing the result of the addition.
-
sum_op<HandlerTy> operator+(product_op<HandlerTy> &&other) const &¶
Overloads the addition operator to combine a product operation with the current sum operation.
- Parameters:
other – A rvalue reference to the product operation to be added.
- Returns:
A new sum operation representing the result of adding the provided product operation.
-
sum_op<HandlerTy> operator+(product_op<HandlerTy> &&other) &&¶
Overloads the addition operator to combine a product operation into a sum operation.
- Parameters:
other – An rvalue reference to a product operation to be added.
- Returns:
A sum operation resulting from the addition of the current instance and the given product operation.
-
sum_op<HandlerTy> operator-(const product_op<HandlerTy> &other) const &¶
Subtracts a product operator from the current sum operator.
- Parameters:
other – A constant reference to the product operator to subtract.
- Returns:
A new sum operator resulting from the subtraction.
-
sum_op<HandlerTy> operator-(const product_op<HandlerTy> &other) &&¶
Subtracts a product operation from a sum operation.
- Parameters:
other – The product operation to subtract from the current sum operation.
- Returns:
A new sum_op instance representing the result of the subtraction.
-
sum_op<HandlerTy> operator-(product_op<HandlerTy> &&other) const &¶
Subtracts a product operator from the current object to form a sum operator.
- Parameters:
other – The product operator to subtract, provided as an rvalue to enable move semantics.
- Returns:
A sum operator resulting from the subtraction operation.
-
sum_op<HandlerTy> operator-(product_op<HandlerTy> &&other) &&¶
Subtracts a product operator from a sum operator.
- Parameters:
other – An rvalue reference to the product operator to be subtracted.
- Returns:
A new sum operator representing the result of the subtraction.
-
sum_op<HandlerTy> operator+(const sum_op<HandlerTy> &other) const &¶
Computes the sum of the current and another sum_op instance.
-
sum_op<HandlerTy> operator+(sum_op<HandlerTy> &&other) &&¶
Overloads the addition operator for a sum_op object.
-
sum_op<HandlerTy> operator-(const sum_op<HandlerTy> &other) const &¶
Subtracts the specified sum_op from this instance.
-
sum_op<HandlerTy> operator-(const sum_op<HandlerTy> &other) &&¶
Subtracts another sum_op instance from the current rvalue sum_op.
-
sum_op<HandlerTy> operator-(sum_op<HandlerTy> &&other) &&¶
Subtracts another sum_op from this instance.
-
sum_op<HandlerTy> &operator*=(const scalar_operator &other)¶
Multiplies the current sum operator by a scalar operator.
- Parameters:
other – The scalar operator to multiply with.
- Returns:
A reference to the modified sum operator.
-
sum_op<HandlerTy> &operator/=(const scalar_operator &other)¶
Performs an in-place division of this operator by the given scalar operator.
- Parameters:
other – The scalar operator to divide by.
- Returns:
A reference to this sum_op after the division.
-
sum_op<HandlerTy> &operator+=(scalar_operator &&other)¶
Adds a scalar operator to the current sum operator.
- Parameters:
other – The scalar operator to add, provided as an rvalue reference.
- Returns:
A reference to the updated sum operator.
-
sum_op<HandlerTy> &operator+=(const scalar_operator &other)¶
Adds a scalar operator to the current sum_op instance.
- Parameters:
other – The scalar_operator to be added.
- Returns:
A reference to the updated sum_op instance.
-
sum_op<HandlerTy> &operator-=(scalar_operator &&other)¶
Subtracts a scalar operator from the current sum operator.
- Parameters:
other – An rvalue reference to a scalar_operator that will be subtracted.
- Returns:
A reference to the updated sum_op instance.
-
sum_op<HandlerTy> &operator-=(const scalar_operator &other)¶
Subtracts a scalar operator from this sum operator.
- Parameters:
other – The scalar operator to subtract from this instance.
- Returns:
A reference to this sum operator after subtraction.
-
sum_op<HandlerTy> &operator*=(const product_op<HandlerTy> &other)¶
Updates the current sum operator by multiplying it with a given product operator.
- Parameters:
other – A constant reference to the product operator to multiply with.
- Returns:
A reference to the updated sum operator instance.
-
sum_op<HandlerTy> &operator+=(const product_op<HandlerTy> &other)¶
Adds the specified product operation to the current sum operation.
- Parameters:
other – The product operation to be incorporated into the sum operation.
- Returns:
A reference to the updated sum operation.
-
sum_op<HandlerTy> &operator+=(product_op<HandlerTy> &&other)¶
Adds the given product operation to the current sum operation.
- Parameters:
other – The product operation to be added (provided as an rvalue reference).
- Returns:
A reference to the updated sum operation.
-
sum_op<HandlerTy> &operator-=(const product_op<HandlerTy> &other)¶
Subtracts the specified product operator from the current sum operator.
- Parameters:
other – The product operator to subtract.
- Returns:
A reference to the modified sum operator.
-
sum_op<HandlerTy> &operator-=(product_op<HandlerTy> &&other)¶
Subtracts a product operator from this sum operator using move semantics.
- Parameters:
other – The product operator to subtract (rvalue reference).
- Returns:
A reference to the modified sum operator.
-
sum_op<HandlerTy> &operator*=(const sum_op<HandlerTy> &other)¶
Performs compound assignment multiplication with another sum_op object.
-
sum_op<HandlerTy> &operator+=(const sum_op<HandlerTy> &other)¶
Adds the contents of the given sum_op instance to this sum_op.
-
sum_op<HandlerTy> &operator+=(sum_op<HandlerTy> &&other)¶
Adds the state of another sum_op object into the current instance using move semantics.
-
sum_op<HandlerTy> &operator-=(const sum_op<HandlerTy> &other)¶
Subtracts the provided sum operator from this instance.
- Parameters:
other – A constant reference to the sum operator to subtract.
- Returns:
A reference to this sum operator after subtraction.
-
sum_op<HandlerTy> &operator-=(sum_op<HandlerTy> &&other)¶
Subtracts the contents of the provided sum_op from this sum_op.
-
std::string to_string() const¶
Return the string representation of the operator.
-
void dump() const¶
Print the string representation of the operator to the standard output.
-
sum_op<HandlerTy> &trim(double tol = 0.0, const std::unordered_map<std::string, std::complex<double>> ¶meters = {})¶
Removes all terms from the sum for which the absolute value of the coefficient is below the given tolerance
-
sum_op<HandlerTy> &canonicalize(const std::set<std::size_t> °rees)¶
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.
-
std::vector<sum_op<HandlerTy>> distribute_terms(std::size_t numChunks) const¶
Distributes the terms into a specified number of chunks.
- Parameters:
numChunks – The number of chunks to distribute the terms into.
- Returns:
A vector of sum_op<HandlerTy> representing the distributed terms.
-
csr_spmatrix to_sparse_matrix(std::unordered_map<std::size_t, std::int64_t> dimensions = {}, const std::unordered_map<std::string, std::complex<double>> ¶meters = {}, bool invert_order = false) const¶
Return the matrix representation of the operator. By default, the matrix is ordered according to the convention (endianness) used in CUDA-Q, and the ordering returned by
degrees
. See the documentation fordegrees
for more detail.dimensions
: A mapping that specifies the number of levels, that is, the dimension of each degree of freedom that the operator acts on. Example for two, 2-level degrees of freedom:{0:2, 1:2}
.parameters
: A map of the parameter names to their concrete, complex values.invert_order
: if set to true, the ordering convention is reversed.
Public Static Functions
-
static sum_op<HandlerTy> empty()¶
Creates and returns an empty sum operator.
- Returns:
An empty sum operator of type sum_op<HandlerTy>.
-
static product_op<HandlerTy> identity()¶
Creates and returns an identity product operator.
- Returns:
A product_op<HandlerTy> representing the identity operator.
-
static product_op<HandlerTy> identity(std::size_t target)¶
Creates an identity product operator for the specified target.
- Parameters:
target – The target index for which the identity operator is created.
- Returns:
A product_op object representing the identity operator for the given target.
Friends
-
template<typename T>
friend sum_op<T> operator*(const scalar_operator &other, const sum_op<T> &self)¶ Multiplies a scalar_operator with a sum_op.
- Parameters:
other – The scalar_operator to multiply.
self – The sum_op to be multiplied.
- Returns:
A new sum_op that is the result of the multiplication.
-
template<typename T>
friend sum_op<T> operator*(const scalar_operator &other, sum_op<T> &&self)¶ Multiplies a scalar operator with a sum operator.
- Parameters:
other – The scalar operator to multiply.
self – The sum operator to be multiplied.
- Returns:
A new sum operator that is the result of the multiplication.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, const sum_op<T> &self)¶ Overloads the + operator to add a scalar_operator to a sum_op.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op to which the scalar_operator is added.
- Returns:
A new sum_op that is the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, sum_op<T> &&self)¶ Overloads the addition operator for combining a scalar_operator with a sum_op.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op to which the scalar_operator is added.
- Returns:
A new sum_op that is the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, const sum_op<T> &self)¶ Overloads the addition operator to add a scalar_operator to a sum_op.
- Template Parameters:
T – The type of the elements in the sum_op.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op to which the scalar_operator is added.
- Returns:
A new sum_op that is the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, sum_op<T> &&self)¶ Overloads the addition operator to add a scalar_operator to a sum_op object.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op object to which the scalar_operator is added.
- Returns:
A new sum_op object that is the result of the addition.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, const sum_op<T> &self)¶ Overloads the subtraction operator for a scalar_operator and a sum_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The sum_op from which the scalar_operator is subtracted.
- Returns:
A new sum_op<T> representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, const product_op<T> &self)¶ Overloads the addition operator to add a scalar_operator to a sum_op.
- Template Parameters:
T – The type of the elements in the sum_op.
- Parameters:
other – The scalar_operator to be added.
self – The sum_op to which the scalar_operator is added.
- Returns:
A new sum_op that is the result of adding the scalar_operator to the sum_op.
-
template<typename T>
friend sum_op<T> operator+(scalar_operator &&other, product_op<T> &&self)¶ Overloads the + operator to add a scalar_operator and a product_op.
- Parameters:
other – The scalar_operator to be added.
self – The product_op to be added.
- Returns:
A sum_op object representing the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, const product_op<T> &self)¶ Overloads the addition operator to add a scalar_operator and a product_op.
- Parameters:
other – The scalar_operator to be added.
self – The product_op to be added.
- Returns:
A sum_op object representing the result of the addition.
-
template<typename T>
friend sum_op<T> operator+(const scalar_operator &other, product_op<T> &&self)¶ Overloads the addition operator to add a scalar_operator to a product_op.
- Template Parameters:
T – The type of the product_op.
- Parameters:
other – The scalar_operator to be added.
self – The product_op to which the scalar_operator is added.
- Returns:
A sum_op object representing the result of the addition.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, const product_op<T> &self)¶ Overloads the subtraction operator for scalar_operator and product_op.
- Parameters:
other – A scalar_operator object to be subtracted.
self – A constant reference to a product_op object.
- Returns:
A sum_op object representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(scalar_operator &&other, product_op<T> &&self)¶ Overloads the subtraction operator for a scalar_operator and a product_op.
- Parameters:
other – The scalar_operator to be subtracted.
self – The product_op from which the scalar_operator is subtracted.
- Returns:
A sum_op object representing the result of the subtraction.
-
template<typename T>
friend sum_op<T> operator-(const scalar_operator &other, const product_op<T> &self)¶ Subtracts a product operator from a scalar operator.
- Template Parameters:
T – The type of the product operator.
- Parameters:
other – The scalar operator to subtract from.
self – The product operator to be subtracted.
- Returns:
The result of the subtraction as a sum_op<T> object.
-
template<typename T>
friend sum_op<T> operator-(const scalar_operator &other, product_op<T> &&self)¶ Overloads the subtraction operator for a scalar_operator and a product_op.
- Parameters:
other – The scalar_operator on the left-hand side of the subtraction.
self – The product_op on the right-hand side of the subtraction, passed as an rvalue reference.
- Returns:
A sum_op<T> representing the result of the subtraction.
-
struct const_iterator¶
Public Functions
-
inline bool operator==(const const_iterator &other) const¶
Equality operator which compares iterators.
-
inline bool operator!=(const const_iterator &other) const¶
Non-equality operator which compares iterators.
-
inline product_op<HandlerTy> &operator*()¶
Dereferences
the iterator to yield a reference to current_val, allowing access to the current product_op.
-
inline product_op<HandlerTy> *operator->()¶
Provides pointer access to the current product_op.
-
inline const_iterator &operator++()¶
Advances the iterator to the next term in the term_map and updates current_val accordingly.
-
inline bool operator==(const const_iterator &other) const¶
-
inline const_iterator begin() const¶
Quantum¶
-
template<std::size_t Levels>
class qudit¶ The qudit models a general d-level quantum system. This type is templated on the number of levels d.
Public Functions
-
inline qudit()¶
Construct a qudit, will allocated a new unique index.
-
inline qudit()¶
-
template<std::size_t N = dyn, std::size_t Levels = 2, typename = std::enable_if_t<(N > 0)>>
class qreg¶ A
qreg
is a container for qudits. This container can be dynamic or compile-time-size specified. By default, theqreg
is constructed as a dynamic register (vector-like) of qubits (2-level). This can be changed via theqreg
type template parameters.Public Functions
-
inline auto begin()¶
Iterator interface, begin.
-
inline value_type &operator[](const std::size_t idx)¶
Returns the qudit at
idx
.
-
inline value_type &front()¶
Returns the first qudit.
-
inline value_type &back()¶
Returns the last qudit.
-
inline qspan<dyn, Levels> slice(std::size_t start, std::size_t size)¶
Returns the
[start, start+size)
qudits.
-
inline std::size_t size() const¶
Returns the number of contained qudits.
-
inline auto begin()¶
-
template<std::size_t Levels = 2>
class qvector¶ A
qvector
is an owning, dynamically sized container for qudits. The semantics of theqvector
follows that of astd::vector
for qudits. It is templated on the number of levels for the held qudits.Public Functions
-
inline qvector(std::size_t size)¶
Construct a
qvector
withsize
qudits in the |0> state.
-
inline explicit qvector(const std::vector<complex> &vector, bool validate)¶
Construct a
qvector
from an input state vector. The number of qubits is determined by the size of the input vector. Ifvalidate
is set, it will check the norm of input state vector.
-
inline explicit qvector(const state &state)¶
Construct a
qvector
from a pre-existingstate
. Thisstate
could be constructed withstate::from_data
or retrieved from an cudaq::get_state.
-
inline auto begin()¶
Iterator interface, begin.
-
inline auto end()¶
Iterator interface, end.
-
inline value_type &operator[](const std::size_t idx)¶
Returns the qudit at
idx
.
-
inline value_type &front()¶
Returns the first qudit.
-
inline qview<Levels> back(std::size_t count)¶
Returns the
[count, size())
qudits as a non-owningqview
-
inline value_type &back()¶
Returns the last qudit.
-
inline qview<Levels> slice(std::size_t start, std::size_t size)¶
Returns the
[start, start+size)
qudits as a non-owningqview
-
inline std::size_t size() const¶
Returns the number of contained qudits.
-
inline qvector(std::size_t size)¶
-
template<std::size_t Levels = 2>
class qview¶ The
qview
represents a non-owning container of qudits.
Common¶
-
class observe_result¶
The observe_result encapsulates all data generated from a cudaq”::”observe call. This includes all measurement counts from the execution of each ansatz + measure circuit, and the global expected value of the spin_op passed to observe.
Public Functions
-
inline observe_result(double e, const spin_op &H)¶
Constructor, takes the precomputed expectation value for <psi(x) | H | psi(x)> for the given spin_op.
-
inline observe_result(double e, const spin_op &H, sample_result counts)¶
Constructor, takes the precomputed expectation value for <psi(x) | H | psi(x)> for the given spin_op. If this execution was shots based, also provide the sample_result data containing counts for each term in H.
-
inline sample_result raw_data()¶
Return the raw counts data for all terms.
- Returns:
-
inline operator double()¶
Conversion operator for this
observe_result
todouble
. Simply returns the precomputed expectation value for the given spin_op. This enables one to ignore the fine-grain sample_result data, and explicitly request the expected value: double exp = cudaq”::”observe(…); as opposed to cudaq”::”observe_data data = cudaq::observe(…); auto exp = data.expectation();.
-
inline double expectation()¶
Return the expected value for the provided spin_op.
- Returns:
-
inline double expectation(const spin_op_term &term)¶
Return the expectation value for a sub-term in the provided spin_op.
-
inline sample_result counts(const spin_op_term &term)¶
Return the counts data for the given spin_op.
-
inline double id_coefficient()¶
Return the coefficient of the identity term. Assumes there is at more one identity term. Returns 0 if no identity term exists.
-
inline void dump()¶
Dump the counts data to standard out.
-
inline observe_result(double e, const spin_op &H)¶
-
struct observe_options¶
Observe options to provide as an argument to the
observe()
,async_observe()
functions.- Param shots:
number of shots to run for the given kernel, or -1 if not applicable.
- Param noise:
noise model to use for the sample operation
- Param num_trajectories:
is the optional number of trajectories to be used when computing the expectation values in the presence of noise. This parameter is only applied to simulation backends that support noisy simulation of trajectories.
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
observe_result cudaq::observe(const observe_options &options, QuantumKernel &&kernel, const spin_op &H, Args&&... args)¶ Compute the expected value of
H
with respect tokernel(Args...)
. Specify the observation options.
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
observe_result cudaq::observe(std::size_t shots, QuantumKernel &&kernel, const spin_op &H, Args&&... args)¶ Compute the expected value of
H
with respect tokernel(Args...)
. Specify the number of shots.This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
observe_result cudaq::observe(QuantumKernel &&kernel, const spin_op &H, Args&&... args)¶ Compute the expected value of
H
with respect tokernel(Args...)
.This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
template<typename QuantumKernel, typename SpinOpContainer, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
std::vector<observe_result> cudaq::observe(QuantumKernel &&kernel, const SpinOpContainer &termList, Args&&... args)¶ Compute the expected value of every
spin_op
provided inSpinOpContainer
(a range concept) with respect tokernel(Args...)
. Return astd::vector<observe_result>
.
-
class ExecutionContext¶
The ExecutionContext is an abstraction to indicate how a CUDA-Q kernel should be executed.
Public Functions
-
inline ExecutionContext(const std::string n)¶
The Constructor, takes the name of the context.
- Parameters:
n – The name of the context
-
inline ExecutionContext(const std::string n, std::size_t shots_)¶
The constructor, takes the name and the number of shots.
- Parameters:
n – The name of the context
shots_ – The number of shots
Public Members
-
const std::string name¶
The name of the context ({basic, sampling, observe})
-
std::size_t shots = 0¶
The number of execution shots.
-
sample_result result¶
Measurement counts for a CUDA-Q kernel invocation.
-
std::optional<double> expectationValue = std::nullopt¶
A computed expectation value.
-
std::optional<cudaq::optimization_result> optResult = std::nullopt¶
An optimization result.
-
bool hasConditionalsOnMeasureResults = false¶
The kernel being executed in this context has conditional statements on measure results.
-
const noise_model *noiseModel = nullptr¶
Noise model to apply to the current execution.
-
bool canHandleObserve = false¶
Flag to indicate if backend can handle spin_op observe task under this ExecutionContext.
-
bool asyncExec = false¶
Flag indicating that the current execution should occur asynchronously.
-
details::future futureResult¶
When execution asynchronously, store the expected results as a cudaq::future here.
-
async_result<sample_result> asyncResult¶
Construct a
async_sample_result
so as to pass across Python boundary.
-
std::unique_ptr<SimulationState> simulationState¶
Pointer to simulation-specific simulation data.
-
std::optional<std::map<std::vector<int>, std::complex<double>>> amplitudeMaps¶
A map of basis-state amplitudes.
-
std::optional<std::pair<const SimulationState*, const SimulationState*>> overlapComputeStates¶
List of pairs of states to compute the overlap.
-
std::optional<std::complex<double>> overlapResult¶
Overlap results.
-
std::string kernelName = ""¶
The name of the kernel being executed.
-
std::size_t batchIteration = 0¶
The current iteration for a batch execution, used by observe_n and sample_n.
-
std::size_t totalIterations = 0¶
For batch execution, the total number of batch iterations.
-
std::vector<std::string> registerNames¶
For mid-circuit measurements in library mode keep track of the register names.
-
std::vector<std::size_t> reorderIdx¶
A vector containing information about how to reorder the global register after execution. Empty means no reordering.
-
std::vector<char> invocationResultBuffer¶
A buffer containing the return value of a kernel invocation. Note: this is only needed for invocation not able to return a
sample_result
.
-
std::optional<std::size_t> numberTrajectories¶
The number of trajectories to be used for an expectation calculation on simulation backends that support trajectory simulation.
-
bool explicitMeasurements = false¶
Whether or not to simply concatenate measurements in execution order.
-
inline ExecutionContext(const std::string n)¶
-
class future¶
The future type models the expected result of a CUDA-Q kernel execution under a specific execution context. This type is returned from asynchronous execution calls. It encapsulates the job-specific circuit execution identifiers, the name of the QPU the job executed on, and any extra configuration information needed to retrieve the results later from the server. This type can be persisted to file and read in later to retrieve execution results. It also optionally wraps a std::future<T> type, and in this case, persistence to file is not allowed, .get() must be invoked at some later point within the same runtime context.
-
template<typename T>
class async_result¶ the async_result type is a user facing, future-like type that is returned from CUDA-Q public asynchronous API functions. It wraps a details::future type, which can itself be constructed from a std::future or a collection of data pertinent to remote QPU REST invocation.
-
using cudaq::async_sample_result = async_result<sample_result>¶
Return type for asynchronous sampling.
-
struct ExecutionResult¶
The
ExecutionResult
models the result of a typical quantum state sampling task. It will contain the observed measurement bit strings and corresponding number of times observed, as well as an expected value with respect to the Z…Z operator.Public Functions
-
std::vector<std::size_t> serialize() const¶
Serialize this sample result to a vector of integers. Encoding: 1st element is size of the register name N, then next N represent register name, next is the number of bitstrings M, then for each bit string a triple {string mapped to long, bit string length, count}.
- Returns:
-
void deserialize(std::vector<std::size_t> &data)¶
Deserialize a vector of integers to a
ExecutionResult
- Parameters:
data – The data with encoding discussed in the brief for
serialize
.
-
ExecutionResult() = default¶
Constructor.
-
ExecutionResult(CountsDictionary c)¶
Construct from a CountsDictionary, assumes registerName == global
- Parameters:
c – the counts
-
ExecutionResult(std::string name)¶
Construct from a register name.
-
ExecutionResult(double expVal)¶
Construct from a precomputed expectation value.
-
ExecutionResult(CountsDictionary c, std::string name)¶
Construct from a
CountsDictionary
, specify the register name.- Parameters:
c – the counts
name – the register name
-
ExecutionResult(CountsDictionary c, double e)¶
Construct from a
CountsDictionary
and expected value.- Parameters:
c – The counts
e – The precomputed expected value
-
ExecutionResult(const ExecutionResult &other)¶
Copy constructor.
- Parameters:
other –
-
ExecutionResult &operator=(const ExecutionResult &other)¶
Set this ExecutionResult equal to the provided one.
- Parameters:
other –
- Returns:
-
bool operator==(const ExecutionResult &result) const¶
Return true if the given
ExecutionResult
is the same as this one.- Parameters:
result –
- Returns:
-
void appendResult(std::string bitString, std::size_t count)¶
Append the bitstring and count to this
ExecutionResult
- Parameters:
bitString –
count –
-
std::vector<std::size_t> serialize() const¶
-
class sample_result¶
The sample_result abstraction wraps a set of
ExecutionResult
s for a single quantum kernel execution under the sampling or observationExecutionContext
. EachExecutionResult
is mapped to a register name, with a defaultExecutionResult
with name global representing the observed measurement results holistically for the quantum kernel.Public Functions
-
sample_result() = default¶
Nullary constructor.
-
sample_result(ExecutionResult &&result)¶
The constructor, sets the global sample result.
-
sample_result(ExecutionResult &result)¶
The constructor, sets the global sample result.
- Parameters:
result –
-
sample_result(std::vector<ExecutionResult> &results)¶
The constructor, appends all provided
ExecutionResult
s.
-
sample_result(double preComputedExp, std::vector<ExecutionResult> &results)¶
The constructor, takes a precomputed expectation value and stores it with the
__global__
ExecutionResult
.
-
sample_result(const sample_result&) = default¶
Copy Constructor.
-
sample_result(sample_result&&) = default¶
Move constructor.
-
sample_result &operator=(sample_result &&counts) = default¶
Move assignment constructor.
-
~sample_result() = default¶
The destructor.
-
bool has_expectation(const std::string_view registerName = GlobalRegisterName) const¶
Return true if the
ExecutionResult
with the specified register name has a precomputed expectation value.
-
void append(ExecutionResult &result, bool concatenate = false)¶
Add another
ExecutionResult
to thissample_result
.- Parameters:
result – Result to append
concatenate – If prior results are found, this concatenates the bitstrings.
-
std::vector<std::string> register_names() const¶
Return all register names. Can be used in tandem with sample_result::to_map(regName : string) to retrieve the counts for each register.
- Returns:
-
sample_result &operator=(sample_result &counts) = default¶
Set this sample_result equal to the provided one.
- Parameters:
counts –
- Returns:
-
sample_result &operator+=(const sample_result &other)¶
Append all the data from other to this sample_result. Merge when necessary.
- Parameters:
other –
- Returns:
-
std::vector<std::size_t> serialize() const¶
Serialize this sample_result. See
ExecutionResult::serialize()
documentation for information.- Returns:
-
void deserialize(std::vector<std::size_t> &data)¶
Create this sample_result from the serialized data.
- Parameters:
data –
-
bool operator==(const sample_result &counts) const¶
Return true if this sample_result is the same as the given one.
- Parameters:
counts –
- Returns:
-
double expectation(const std::string_view registerName = GlobalRegisterName) const¶
Return the expected value <Z…Z>
- Returns:
-
double probability(std::string_view bitString, const std::string_view registerName = GlobalRegisterName) const¶
Return the probability of observing the given bit string.
- Parameters:
bitString –
- Returns:
-
std::string most_probable(const std::string_view registerName = GlobalRegisterName) const¶
Return the most probable bit string.
- Parameters:
registerName –
- Returns:
-
std::size_t count(std::string_view bitString, const std::string_view registerName = GlobalRegisterName) const¶
Return the number of times the given bitstring was observed.
- Parameters:
bitString –
- Returns:
-
std::size_t size(const std::string_view registerName = GlobalRegisterName) const noexcept¶
Return the number of observed bit strings.
- Returns:
-
void dump() const¶
Dump this sample_result to standard out.
-
void dump(std::ostream &os) const¶
Dump this sample_result to the given output stream.
-
void clear()¶
Clear this sample_result.
-
CountsDictionary to_map(const std::string_view registerName = GlobalRegisterName) const¶
Extract the ExecutionResults as a std::unordered<string, size_t> map.
- Parameters:
registerName –
- Returns:
-
inline sample_result get_marginal(const std::vector<std::size_t> &&marginalIndices, const std::string_view registerName = GlobalRegisterName) const¶
Extract marginal counts, that is those counts for a subset of measured qubits.
- Parameters:
marginalIndices – The qubit indices as an
rvalue
registerName –
- Returns:
-
sample_result get_marginal(const std::vector<std::size_t> &marginalIndices, const std::string_view registerName = GlobalRegisterName) const¶
Extract marginal counts, that is those counts for a subset of measured qubits.
- Parameters:
marginalIndices – The qubit indices as an reference
registerName –
- Returns:
-
void reorder(const std::vector<std::size_t> &index, const std::string_view registerName = GlobalRegisterName)¶
Reorder the bits in an ExecutionResult.
- Parameters:
index – Vector of indices such that
newBitStr(:)=oldBitStr(index(:))
registerName – register name to process (defaults to global)
-
CountsDictionary::iterator begin()¶
Range-based iterator begin function.
- Returns:
-
CountsDictionary::iterator end()¶
Range-based iterator end function.
- Returns:
-
CountsDictionary::const_iterator cbegin() const¶
Range-based constant iterator begin function.
- Returns:
-
CountsDictionary::const_iterator cend() const¶
Range-based constant iterator end function.
- Returns:
-
inline CountsDictionary::const_iterator begin() const¶
Range-based constant iterator begin function.
- Returns:
-
inline CountsDictionary::const_iterator end() const¶
Range-based constant iterator end function.
- Returns:
-
inline std::size_t get_total_shots() const¶
Get the total number of shots in the result.
Public Static Functions
-
static bool has_even_parity(std::string_view bitString)¶
Return true if the bit string has even parity.
- Parameters:
bitString –
- Returns:
-
sample_result() = default¶
-
struct sample_options¶
Sample options to provide to the sample() / async_sample() functions.
- Param shots:
number of shots to run for the given kernel
- Param noise:
noise model to use for the sample operation
- Param explicit_measurements:
whether or not to form the global register based on user-supplied measurement order.
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
sample_result cudaq::sample(const sample_options &options, QuantumKernel &&kernel, Args&&... args)¶ Sample the given quantum kernel expression and return the mapping of observed bit strings to corresponding number of times observed.
Given a quantum kernel with void return type, sample the corresponding quantum circuit generated by the kernel expression, returning the mapping of bits observed to number of times it was observed.
- Parameters:
options – Sample options.
kernel – The kernel expression, must contain final measurements.
args – The variadic concrete arguments for evaluation of the kernel.
- Returns:
The counts dictionary.
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
auto cudaq::sample(std::size_t shots, QuantumKernel &&kernel, Args&&... args)¶ Sample the given quantum kernel expression and return the mapping of observed bit strings to corresponding number of times observed. Specify the number of shots.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Given a quantum kernel with void return type, sample the corresponding quantum circuit generated by the kernel expression, returning the mapping of bits observed to number of times it was observed.
- Parameters:
shots – The number of samples to collect.
kernel – The kernel expression, must contain final measurements.
args – The variadic concrete arguments for evaluation of the kernel.
- Returns:
The counts dictionary.
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_r_v<void, QuantumKernel, Args...>>>
sample_result cudaq::sample(QuantumKernel &&kernel, Args&&... args)¶ Sample the given quantum kernel expression and return the mapping of observed bit strings to corresponding number of times observed.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Given a quantum kernel with void return type, sample the corresponding quantum circuit generated by the kernel expression, returning the mapping of bits observed to number of times it was observed.
- Parameters:
kernel – the kernel expression, must contain final measurements
args – the variadic concrete arguments for evaluation of the kernel.
- Returns:
counts, The counts dictionary.
-
class SimulationState¶
The
SimulationState
interface provides and extension point for concrete circuit simulation sub-types to describe their underlying quantum state data in an efficient manner. TheSimulationState
provides a handle on the data for clients, with data remaining on GPU device or CPU memory. The primary goal of this type and its sub-types is to minimize data transfers for the state.Subclassed by cudaq::CusvState< ScalarType >, cudaq::QPUState, cudaq::RemoteSimulationState, nvqir::MPSSimulationState< ScalarType >, nvqir::TensorNetSimulationState< ScalarType >
-
struct Tensor¶
Simulation states are made up of a vector of Tensors. Each tensor tracks its data pointer and the tensor extents.
-
enum class cudaq::SimulationState::precision¶
Runtime-known precision for the simulation data.
Values:
-
enumerator fp32¶
-
enumerator fp64¶
-
enumerator fp32¶
-
enum class cudaq::simulation_precision¶
Define an enumeration of possible simulation floating point precision types.
Values:
-
enumerator fp32¶
-
enumerator fp64¶
-
enumerator fp32¶
-
using cudaq::tensor = SimulationState::Tensor¶
-
using cudaq::TensorStateData = std::vector<std::pair<const void*, std::vector<std::size_t>>>¶
Encapsulates a list of tensors (data pointer and dimensions).
-
using cudaq::state_data = std::variant<std::vector<std::complex<double>>, std::vector<std::complex<float>>, std::pair<std::complex<double>*, std::size_t>, std::pair<std::complex<float>*, std::size_t>, TensorStateData>¶
state_data is a variant type encoding different forms of user state vector data we support.
-
template<typename ScalarType>
class CusvState : public cudaq::SimulationState¶ CusvState provides an implementation of
SimulationState
that encapsulates the state data for the Custatevec Circuit Simulator. It attempts to keep the simulation data on GPU device and care is taken to ensure operations and comparisons with other states operate on compatible floating point element types.
-
template<typename ScalarType = double>
class MPSSimulationState : public cudaq::SimulationState¶
-
template<typename ScalarType = double>
class TensorNetSimulationState : public cudaq::SimulationState¶
-
class RemoteSimulationState : public cudaq::SimulationState¶
Implementation of
SimulationState
for remote simulator backends.
-
class QPUState : public cudaq::SimulationState¶
Implementation of
SimulationState
for quantum device backends. The state is represented by a quantum kernel. Quantum state contains all the information we need to replicate a call to kernel that created the state.
-
template<typename T>
class RegisteredType¶ RegisteredType allows interface types to declare themselves as plugin interfaces. Used as follows class MyInterface : public RegisteredType<MyInterface> {…};.
-
class complex_matrix¶
This is a minimalist matrix container. It is two-dimensional. It owns its data. Elements are of type
complex<double>
. Typically, it will contain a two-by-two set of values.Public Functions
-
value_type minimal_eigenvalue() const¶
Return the minimal eigenvalue for this matrix.
-
std::vector<value_type> eigenvalues() const¶
Return this matrix’s eigenvalues.
-
complex_matrix eigenvectors() const¶
Return the eigenvectors of this matrix. They are returned as the rows of a new matrix.
-
void set_zero()¶
Resets the matrix to all zero entries. Not needed after construction since the matrix will be initialized to zero.
-
complex_matrix exponential()¶
Matrix exponential, uses 20 terms of Taylor Series approximation.
-
complex_matrix power(int powers)¶
Matrix power.
-
complex_matrix adjoint()¶
Returns the conjugate transpose of a matrix.
-
complex_matrix::value_type operator[](const std::vector<std::size_t> &at) const¶
Operator to get the value at a particular index in the matrix.
-
complex_matrix::value_type &operator[](const std::vector<std::size_t> &at)¶
Operator to get the value at a particular index in the matrix.
-
complex_matrix::value_type operator()(std::size_t i, std::size_t j) const¶
Operator to get the value at a particular index in the matrix.
-
complex_matrix::value_type &operator()(std::size_t i, std::size_t j)¶
Operator to get the value at a particular index in the matrix.
-
std::string to_string() const¶
Returns a string representation of the matrix.
-
void dump() const¶
Print this matrix to the standard output stream.
-
void dump(std::ostream &os) const¶
Print this matrix to the given output stream.
Public Static Functions
-
static complex_matrix identity(const std::size_t rows)¶
Return a square identity matrix for the given size.
Friends
-
friend complex_matrix operator*(const complex_matrix&, const complex_matrix&)¶
Multiplication (cross-product) of two matrices.
-
friend std::vector<complex_matrix::value_type> operator*(const complex_matrix&, const std::vector<complex_matrix::value_type>&)¶
Right-side multiplication with a vector.
-
friend complex_matrix operator*(complex_matrix::value_type, const complex_matrix&)¶
Scalar Multiplication with matrices.
-
friend complex_matrix operator+(const complex_matrix&, const complex_matrix&)¶
Addition of two matrices.
-
friend complex_matrix operator-(const complex_matrix&, const complex_matrix&)¶
Subtraction of two matrices.
-
friend complex_matrix kronecker(const complex_matrix&, const complex_matrix&)¶
Kronecker of two matrices.
-
template<typename Iterable, typename T>
friend complex_matrix kronecker(Iterable begin, Iterable end)¶ Kronecker a list of matrices. The list can be any container that has iterators defined.
-
value_type minimal_eigenvalue() const¶
-
class Trace¶
A trace is a circuit representation of the executed computation, as seen by the execution manager. (Here, a circuit is represented as a list of instructions on qudits). Since the execution manager cannot “see” control flow, the trace of a kernel with control flow represents a single execution path, and thus two calls to the same kernel might produce traces.
-
template<typename ElementType, typename = std::enable_if_t<std::is_integral_v<ElementType> && std::is_signed_v<ElementType>>>
inline std::vector<ElementType> cudaq::range(ElementType N)¶ Return a vector of integers. The first element is zero, and the remaining elements are all values incremented by 1 to the total size value provided (exclusive).
-
template<typename ElementType, typename = std::enable_if_t<std::is_integral_v<ElementType> && std::is_signed_v<ElementType>>>
inline std::vector<ElementType> cudaq::range(ElementType start, ElementType stop, ElementType step = 1)¶ Return a vector of integers. The first element is the user-specified
start
value. The remaining values are all values incremented bystep
(defaults to 1) until thestop
value is reached (exclusive).
-
template<typename QuantumKernel, typename ...Args, typename = std::enable_if_t<std::is_invocable_v<QuantumKernel, Args...>>>
std::string cudaq::draw(QuantumKernel &&kernel, Args&&... args)¶ Returns a drawing of the execution path, i.e., the trace, of the kernel. The drawing is a UTF-8 encoded string.
Usage:
#include <cudaq.h> #include <cudaq/algorithms/draw.h> #include <iostream> auto bell_pair = []() __qpu__ { cudaq::qvector q(2); h(q[0]); x<cudaq::ctrl>(q[0], q[1]); mz(q); }; ... std::cout << cudaq::draw(bell_pair); /* Output: ╭───╮ q0 : ┤ h ├──●── ╰───╯╭─┴─╮ q1 : ─────┤ x ├ ╰───╯ */ auto kernel = [](float angle) __qpu__ { cudaq::qvector q(1); h(q[0]); ry(angle, q[0]); }; ... std::cout << cudaq::draw(kernel, 0.59); /* Output: ╭───╮╭──────────╮ q0 : ┤ h ├┤ ry(0.59) ├ ╰───╯╰──────────╯ */
- Parameters:
kernel – The quantum callable with non-trivial function signature.
args – The arguments required for evaluation of the quantum kernel.
- Returns:
The UTF-8 encoded string of the circuit, without measurement operations.
-
template<typename QuantumKernel, typename ...Args>
auto cudaq::get_state(QuantumKernel &&kernel, Args&&... args)¶ Return the state representation generated by the kernel at the given runtime arguments.
-
class Resources¶
The Resources type encodes information regarding the currently executing kernel’s resource usage. This includes number and type of quantum operation, circuit depth, etc.
-
using cudaq::complex_matrix::value_type = std::complex<double>¶
Noise Modeling¶
-
template<typename Channel, typename ...Args>
void cudaq::apply_noise(Args&&... args)¶ 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
__qpu__
). The functionality is only supported for simulation targets, so it is automatically (and silently) stripped from any programs submitted to hardware targets.- Template Parameters:
Channel –
A subtype of
cudaq::kraus_channel
that implements/defines the desired noise mechanisms as Kraus channels (e.g.cudaq::depolarization2
). If you want to use a customcudaq::kraus_channel
(i.e. not built-in to CUDA-Q), it must first be registered outside the kernel withcudaq::noise_model::register_channel()
, like this:struct my_custom_kraus_channel_subtype : public ::cudaq::kraus_channel { static constexpr std::size_t num_parameters = 1; static constexpr std::size_t num_targets = 1; my_custom_kraus_channel_subtype(const std::vector<cudaq::real> ¶ms) { std::vector<cudaq::complex> k0v{std::sqrt(1 - params[0]), 0, 0, std::sqrt(1 - params[0])}, k1v{0, std::sqrt(params[0]), std::sqrt(params[0]), 0}; push_back(cudaq::kraus_op(k0v)); push_back(cudaq::kraus_op(k1v)); validateCompleteness(); generateUnitaryParameters(); } REGISTER_KRAUS_CHANNEL("my_custom_kraus_channel_subtype"); }; cudaq::noise_model noise; noise.register_channel<my_custom_kraus_channel_subtype>();
- Parameters:
args –
The precise argument pack depend on the concrete
Channel
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:cudaq::qubit q, r; cudaq::apply_noise<cudaq::depolarization2>(/*probability=*/0.1, q, r);
-
struct kraus_op¶
A kraus_op represents a single Kraus operation, described as a complex matrix of specific size. The matrix is represented here as a 1d array (specifically a std::vector).
Public Functions
Public Members
-
std::size_t nRows = 0¶
The number of rows in the matrix.
-
std::size_t nCols = 0¶
The number of columns in the matrix NOTE we currently assume nRows == nCols.
-
const cudaq::simulation_precision precision = std::is_same_v<cudaq::real, float> ? cudaq::simulation_precision::fp32 : cudaq::simulation_precision::fp64¶
The precision of the underlying data.
-
std::size_t nRows = 0¶
-
class kraus_channel¶
A kraus_channel represents a quantum noise channel on specific qubits. The action of the noise channel is described by a vector of Kraus operations - matrices with size equal to 2**nQubits x 2**nQubits, where the number of qubits is the number of provided qubit indices at construction.
Subclassed by cudaq::amplitude_damping_channel, cudaq::bit_flip_channel, cudaq::depolarization2, cudaq::depolarization_channel, cudaq::pauli1, cudaq::pauli2, cudaq::phase_damping, cudaq::phase_flip_channel, cudaq::y_error
Public Functions
-
kraus_channel() = default¶
The nullary constructor.
-
kraus_channel(const kraus_channel &other)¶
The copy constructor.
- Parameters:
other –
-
template<typename ...T>
inline kraus_channel(std::initializer_list<T>&&... inputLists)¶ The constructor, initializes kraus_ops internally from the provided initializer_lists.
-
inline kraus_channel(const std::vector<kraus_op> &inOps)¶
The constructor, take qubits and channel kraus_ops as lvalue reference.
-
inline kraus_channel(std::vector<kraus_op> &&ops)¶
The constructor, take qubits and channel kraus_ops as rvalue reference.
-
std::size_t size() const¶
Return the number of kraus_ops that make up this channel.
-
bool empty() const¶
Return true if there are no ops in this channel.
-
kraus_channel &operator=(const kraus_channel &other)¶
Set this kraus_channel equal to the given one.
-
inline bool is_unitary_mixture() const¶
Returns whether or not this is a unitary mixture.
-
inline void generateUnitaryParameters()¶
Checks if Kraus ops have unitary representations and saves them if they do. Users should only need to call this if they have modified the Kraus ops and want to recompute these values.
Public Members
-
noise_model_type noise_type = noise_model_type::unknown¶
Noise type enumeration.
-
std::vector<double> parameters¶
Noise parameter values.
-
std::vector<std::vector<std::complex<double>>> unitary_ops¶
If all Kraus ops are - when scaled - unitary, this holds the unitary versions of those ops. These values are always “double” regardless of whether cudaq::real is float or double.
-
std::vector<double> probabilities¶
If all Kraus ops are - when scaled - unitary, this holds the probabilities of those ops. These values are always “double” regardless of whether cudaq::real is float or double.
-
kraus_channel() = default¶
-
class amplitude_damping_channel : public cudaq::kraus_channel¶
amplitude_damping_channel is a kraus_channel that automates the creation of the kraus_ops that make up a single-qubit amplitude damping error channel.
Subclassed by cudaq::amplitude_damping
-
class bit_flip_channel : public cudaq::kraus_channel¶
bit_flip_channel is a kraus_channel that automates the creation of the kraus_ops that make up a single-qubit bit flipping error channel.
Subclassed by cudaq::x_error
-
class phase_flip_channel : public cudaq::kraus_channel¶
phase_flip_channel is a kraus_channel that automates the creation of the kraus_ops that make up a single-qubit phase flip error channel.
Subclassed by cudaq::z_error
-
class depolarization_channel : public cudaq::kraus_channel¶
depolarization_channel is a kraus_channel that automates the creation of the kraus_ops that make up a single-qubit depolarization error channel.
Subclassed by cudaq::depolarization1
-
class x_error : public cudaq::bit_flip_channel¶
x_error is a Pauli error that applies the X operator when an error occurs. It is the same as bit_flip_channel.
-
class y_error : public cudaq::kraus_channel¶
Y_error is a Pauli error that applies the Y operator when an error occurs.
-
class z_error : public cudaq::phase_flip_channel¶
z_error is a Pauli error that applies the Z operator when an error occurs. It is the same as phase_flip_channel.
-
class amplitude_damping : public cudaq::amplitude_damping_channel¶
amplitude_damping is the same as amplitude_damping_channel.
-
class phase_damping : public cudaq::kraus_channel¶
phase_damping is a kraus_channel that automates the creation of the kraus_ops that make up a single-qubit phase damping error channel.
-
class pauli1 : public cudaq::kraus_channel¶
A single-qubit Pauli error that applies either an X error, Y error, or Z error, with 3 probabilities specified as inputs.
Public Functions
-
class pauli2 : public cudaq::kraus_channel¶
A 2-qubit Pauli error that applies one of the following errors, with the probabilities specified as inputs. Possible errors: IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, and ZZ.
Public Functions
-
inline pauli2(const std::vector<cudaq::real> &p)¶
Construct a 2-qubit Pauli error Kraus channel.
- Parameters:
p – Error probabilities for the 2-qubit Pauli operators. The length of this vector must be 15. Note that since the probability of II is not specified, it is implied to by 1 - sum(p). Therefore, maximal mixing occurs when sum(p) = 0.9375.
Public Static Attributes
-
static constexpr std::size_t num_parameters = 15¶
Number of parameters. The 15 parameters are the probability that each one of the above errors will happen. Only 1 of the 15 possible errors will happen (at most).
-
static constexpr std::size_t num_targets = 2¶
Number of targets.
-
inline pauli2(const std::vector<cudaq::real> &p)¶
-
class depolarization1 : public cudaq::depolarization_channel¶
depolarization1 is the same as depolarization_channel
-
class depolarization2 : public cudaq::kraus_channel¶
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.
Public Functions
-
inline depolarization2(const real probability)¶
Construct a two qubit Kraus channel that applies a depolarization channel on either qubit independently.
- Parameters:
probability – The probability of any depolarizing error happening in the 2 qubits. (Setting this to 1.0 ensures that “II” cannot happen; maximal mixing occurs at p = 0.9375.)
Public Static Attributes
-
static constexpr std::size_t num_parameters = 1¶
Number of parameters. The 1 parameter is the probability that each one of the 15 error possibilities list above will occur. Only 1 of the 15 possible errors will happen (at most).
-
static constexpr std::size_t num_targets = 2¶
Number of targets.
-
inline depolarization2(const real probability)¶
-
class noise_model¶
The noise_model type keeps track of a set of kraus_channels to be applied after the execution of quantum operations. Each quantum operation maps to a Kraus channel containing a number of kraus_ops to be applied to the density matrix representation of the state.
Public Types
-
using PredicateFuncTy = std::function<kraus_channel(const std::vector<std::size_t>&, const std::vector<double>&)>¶
Callback function type for noise channel. Given the qubit operands and gate parameters, this function should return a concrete noise channel.
Public Functions
-
noise_model()¶
default constructor
-
inline bool empty() const¶
Return true if there are no kraus_channels in this noise model.
- Returns:
-
void add_channel(const std::string &quantumOp, const std::vector<std::size_t> &qubits, const kraus_channel &channel)¶
Add the Kraus channel to the specified one-qubit quantum operation. It applies to the quantumOp operation for the specified qubits in the kraus_channel.
-
void add_channel(const std::string &quantumOp, const PredicateFuncTy &pred)¶
Add the Kraus channel as a callback to the specified quantum operation.
- Parameters:
quantumOp – Quantum operation that the noise channel applies to.
pred – Callback function that generates a noise channel.
-
template<typename KrausChannelT, typename = requires_constructor<KrausChannelT, const std::vector<cudaq::real>&>>
inline void register_channel()¶ Register a Kraus channel. This must be called outside of a CUDA-Q kernel before the channel can be recognized inside a CUDA-Q kernel.
-
void add_all_qubit_channel(const std::string &quantumOp, const kraus_channel &channel, int numControls = 0)¶
Add the Kraus channel that applies to a quantum operation on any arbitrary qubits.
- Parameters:
quantumOp – Quantum operation that the noise channel applies to.
channel – The Kraus channel to apply.
numControls – Number of control qubits for the gate. Default is 0 (gate without a control modifier).
-
template<typename ...QuantumOp>
inline void add_channel(const std::vector<std::size_t> &qubits, const kraus_channel &channel)¶ Add the provided kraus_channel to all specified quantum operations.
-
template<typename ...QuantumOp>
inline void add_channel(const PredicateFuncTy &pred)¶ Add the provided kraus_channel callback to all specified quantum operations.
-
template<typename ...QuantumOp>
inline void add_all_qubit_channel(const kraus_channel &channel, int numControls = 0)¶ Add the provided kraus_channel to all specified quantum operations applying on arbitrary qubits.
-
std::vector<kraus_channel> get_channels(const std::string &quantumOp, const std::vector<std::size_t> &targetQubits, const std::vector<std::size_t> &controlQubits = {}, const std::vector<double> ¶ms = {}) const¶
Return relevant kraus_channels on the specified qubits for.
-
template<typename QuantumOp>
inline std::vector<kraus_channel> get_channels(const std::vector<std::size_t> &targetQubits, const std::vector<std::size_t> &controlQubits = {}, const std::vector<double> ¶ms = {}) const¶ Get all kraus_channels on the given qubits.
-
using PredicateFuncTy = std::function<kraus_channel(const std::vector<std::size_t>&, const std::vector<double>&)>¶
-
enum class cudaq::noise_model_type¶
Values:
-
enumerator unknown¶
-
enumerator depolarization_channel¶
-
enumerator amplitude_damping_channel¶
-
enumerator bit_flip_channel¶
-
enumerator phase_flip_channel¶
-
enumerator x_error¶
-
enumerator y_error¶
-
enumerator z_error¶
-
enumerator amplitude_damping¶
-
enumerator phase_damping¶
-
enumerator pauli1¶
-
enumerator pauli2¶
-
enumerator depolarization1¶
-
enumerator depolarization2¶
-
enumerator unknown¶
Kernel Builder¶
-
template<typename ...Args>
class kernel_builder : public cudaq::details::kernel_builder_base¶ Public Functions
-
inline kernel_builder(std::vector<details::KernelBuilderType> &types)¶
The constructor, takes the input
KernelBuilderType
s which is used to create the MLIR function type.
-
inline auto &getArguments()¶
Return the
QuakeValue
arguments.
-
inline bool isArgStdVec(std::size_t idx)¶
Return
true
if the argument to the kernel is astd::vector
,false
otherwise.
-
inline std::string name()¶
Return the name of this kernel.
-
inline std::size_t getNumParams()¶
Return the number of function arguments.
- Returns:
-
inline QuakeValue qalloc()¶
Return a
QuakeValue
representing the allocated qubit.
-
inline QuakeValue qalloc(const std::size_t nQubits)¶
Return a
QuakeValue
representing the allocatedQVec
.
-
inline QuakeValue qalloc(QuakeValue size)¶
Return a
QuakeValue
representing the allocatedVeq
, size is from a pre-allocated sizeQuakeValue
orBlockArgument
.
-
inline QuakeValue qalloc(std::vector<std::complex<double>> &state)¶
Return a
QuakeValue
representing the allocated quantum register, initialized to the given state vector,state
.Note: input argument is a true reference here, the calling context has to own the data. Specifically, the builder object will capture variables by reference (implemented as a container of pointers for simplicity) but the builder does not create, own, or copy these vectors. This implies that if the captured vector goes out of scope before the kernel is invoked, the reference may contain garbage. This behavior is identical to a C++ lambda capture by reference.
-
inline QuakeValue constantVal(double val)¶
Return a
QuakeValue
representing the constant floating-point value.
-
inline void swap(const QuakeValue &first, const QuakeValue &second)¶
SWAP operation for swapping the quantum states of two qubits.
-
template<typename mod, typename = typename std::enable_if_t<std::is_same_v<mod, cudaq::ctrl>>>
inline void swap(const QuakeValue &control, const QuakeValue &first, const QuakeValue &second)¶ SWAP operation for performing a Fredkin gate between two qubits, based on the state of input
control
qubit/s.
-
template<typename mod, typename = typename std::enable_if_t<std::is_same_v<mod, cudaq::ctrl>>>
inline void swap(const std::vector<QuakeValue> &controls, const QuakeValue &first, const QuakeValue &second)¶ SWAP operation for performing a Fredkin gate between two qubits, based on the state of an input vector of
controls
.
-
inline kernel_builder(std::vector<details::KernelBuilderType> &types)¶
-
class QuakeValue¶
A QuakeValue is meant to provide a thin wrapper around an mlir::Value instance. These QuakeValues represent handles to function arguments and return values from MLIR Operations, specifically Quake Dialect operations. The QuakeValue also exposes and algebraic API enabling one to negate, add, subtract, and multiply QuakeValues with each other as well as with primitive arithmetic types, e.g. double.
Public Functions
-
mlir::Value getValue() const¶
Return the actual MLIR Value.
-
QuakeValue(mlir::ImplicitLocOpBuilder &builder, mlir::Value v)¶
The constructor, takes the builder and the value to wrap.
-
QuakeValue(mlir::ImplicitLocOpBuilder &builder, double v)¶
The constructor, takes the builder and a constant double value, which will map to an arith::ConstantFloatOp Value.
-
void dump()¶
Dump the QuakeValue to standard out.
-
void dump(std::ostream&)¶
Dump the QuakeValue to the given output stream.
-
inline bool canValidateNumElements()¶
Return true if this QuakeValue of StdVecType can validate its number of unique elements. We cannot do this in the case of QuakeValue extractions within for loops where we do not know the bounds of the loop.
-
QuakeValue slice(const std::size_t startIdx, const std::size_t count)¶
For a subscriptable QuakeValue, extract a sub set of the elements starting at the given startIdx and including the following count elements.
-
QuakeValue size()¶
For a QuakeValue with type StdVec or Veq, return the size QuakeValue.
-
std::optional<std::size_t> constantSize()¶
Return the constant size of this QuakeValue if it is of Veq type.
-
bool isStdVec()¶
Return true if this QuakeValue is of type StdVec.
- Returns:
-
std::size_t getRequiredElements()¶
For a QuakeValue of type StdVec, return the number of required elements, i.e. the number of unique extractions observed.
-
QuakeValue operator[](const std::size_t idx)¶
Return a new QuakeValue when the current value is indexed, specifically for QuakeValues of type StdVecType and VeqType.
-
QuakeValue operator[](const QuakeValue &idx)¶
Return a new QuakeValue when the current value is indexed, specifically for QuakeValues of type StdVecType and VeqType.
-
QuakeValue operator-() const¶
Return the negation of this QuakeValue.
-
QuakeValue operator*(const double)¶
Multiply this QuakeValue by the given double.
-
QuakeValue operator*(QuakeValue other)¶
Multiply this QuakeValue by the given QuakeValue.
-
QuakeValue operator/(const double)¶
Divide this QuakeValue by the given double.
-
QuakeValue operator/(QuakeValue other)¶
Divide this QuakeValue by the given QuakeValue.
-
QuakeValue operator+(const double)¶
Add this QuakeValue with the given double.
-
QuakeValue operator+(const int)¶
Add this QuakeValue with the given int.
-
QuakeValue operator+(QuakeValue other)¶
Add this QuakeValue with the given QuakeValue.
-
QuakeValue operator-(const double)¶
Subtract the given double from this QuakeValue.
-
QuakeValue operator-(const int)¶
Subtract the given int from this QuakeValue.
-
QuakeValue operator-(QuakeValue other)¶
Subtract the given QuakeValue from this QuakeValue.
-
QuakeValue inverse() const¶
Return the inverse (1/x) of this QuakeValue.
-
mlir::Value getValue() const¶
-
class kernel_builder_base¶
The
kernel_builder_base
provides a base type for the templated kernel builder so that we can get a single handle on an instance within the runtime.Subclassed by cudaq::kernel_builder< Args >
Friends
-
friend std::ostream &operator<<(std::ostream &stream, const kernel_builder_base &builder)¶
Write the kernel_builder to the given output stream. This outputs the Quake representation.
-
friend std::ostream &operator<<(std::ostream &stream, const kernel_builder_base &builder)¶
-
class KernelBuilderType¶
The
kernel_builder::Type
allows us to track input C++ types representing the quake function argument types in a way that does not expose MLIR Type to the CUDA-Q code. This type keeps track of a functor that generates the MLIR Type in implementation code when create() is invoked.
Algorithms¶
-
class optimizer¶
The cudaq::optimizer provides a high-level interface for general optimization of user-specified objective functions. This is meant to serve an interface for clients working with concrete subtypes providing specific optimization algorithms possibly delegating to third party libraries. This interface provides an optimize(…) method that takes the number of objective function input parameters (the dimension), and a user-specified objective function that takes the function input parameters as a immutable (
const
) vector<double> reference and a mutable vector<double> reference modeling the current iteration gradient vector (dF / dx_i, for all i parameters). This function must return a scalar double, the value of this function at the current input parameters. The optimizer also exposes a method for querying whether the current optimization strategy requires gradients or not. Parameterizing optimization strategies is left as a task for sub-types (things like initial parameters, max function evaluations, etc.).cudaq::optimizers::cobyla opt; assert(!opt.requiresGradients() && "Cobyla algo does not use gradients."); auto [opt_val, opt_params] = opt.optimize(2, [&](const std::vector<double>& x, std::vector<double>& dx) { ... use x, modify dx, return scalar double ... } );
Public Functions
-
virtual bool requiresGradients() = 0¶
Returns true if this optimization strategy requires gradients to achieve its optimization goals.
-
virtual optimization_result optimize(const int dim, optimizable_function &&opt_function) = 0¶
Run the optimization strategy defined by concrete sub-type implementations. Takes the number of variational parameters, and a custom objective function that takes the function input parameters as a immutable (
const
) vector<double> reference and a mutable vector<double> reference modeling the current iteration gradient vector (dF / dx_i, for all i parameters). This function must return a scalar double, the value of this function at the current input parameters.
-
virtual bool requiresGradients() = 0¶
-
class optimizable_function¶
An optimizable_function wraps a user-provided objective function to be optimized.
-
using cudaq::optimization_result = std::tuple<double, std::vector<double>>¶
Typedef modeling the result of an optimization strategy, a double representing the optimal value and the corresponding optimal parameters.
-
class state¶
The cudaq::state encapsulate backend simulation state vector or density matrix data.
Public Functions
-
inline explicit state(SimulationState *ptrToOwn)¶
The constructor, takes the simulation data and owns it.
-
std::complex<double> operator[](std::size_t idx) const¶
Convenience function for extracting from a known vector.
-
std::complex<double> operator()(std::size_t idx, std::size_t jdx) const¶
Convenience function for extracting from a known matrix.
-
std::complex<double> operator()(const std::initializer_list<std::size_t>&, std::size_t tensorIdx = 0) const¶
General extraction operator for state data.
-
tensor get_tensor(std::size_t tensorIdx = 0) const¶
Return the tensor at the given index for this state representation. For state-vector and density matrix simulation states, there is just one tensor with rank 1 or 2 respectively.
-
std::size_t get_num_tensors() const¶
Return the number of tensors that represent this state.
-
std::size_t get_num_qubits() const¶
Return the number of qubits.
-
SimulationState::precision get_precision() const¶
Return the underlying floating point precision for this state.
-
bool is_on_gpu() const¶
Return true if this a state on the GPU.
-
template<typename ScalarType>
inline void to_host(std::complex<ScalarType> *hostPtr, std::size_t numElements) const¶ Copy this state from device to.
-
void dump() const¶
Dump the state to standard out.
-
void dump(std::ostream &os) const¶
Dump the state to given output stream.
-
std::complex<double> overlap(const state &other)¶
Compute the overlap of this state with the other one. For state vectors (pure states), it is computed as
|<this | other>|
.
-
std::complex<double> amplitude(const std::vector<int> &basisState)¶
Return the amplitude of the given computational basis state.
-
std::vector<std::complex<double>> amplitudes(const std::vector<std::vector<int>> &basisStates)¶
Return the amplitudes of the given list of computational basis states.
Public Static Functions
-
static state from_data(const state_data &data)¶
Create a new state from user-provided data. The data can be host or device data.
-
inline explicit state(SimulationState *ptrToOwn)¶
-
class gradient¶
The cudaq::gradient represents a base type for all gradient strategies leveraged by variational algorithms.
The cudaq::gradient tracks a std::function with signature void(std::vector<double>) representing the parameterized kernel ansatz. For ansatzes that do not follow this signature, a separate Argument Mapper must be provided which takes std::vector<double> to a tuple of custom function arguments. All gradient subtypes should inherit the base class constructors (using gradient::gradient), but provide a concrete implementation of gradient::compute(). The compute method takes as input the current iteration parameters, a reference to the gradient vector which compute() must update, the cudaq::spin_op for this variational algorithm, and the expected value of the spin_op at the current iteration’s parameters. Subtypes can leverage the protected gradient::getExpectedValue() method to compute <psi(x) | H | psi(x)> at the provided set of variational parameters.
Subclassed by cudaq::gradients::central_difference, cudaq::gradients::forward_difference, cudaq::gradients::parameter_shift
Public Functions
-
inline gradient(std::function<void(std::vector<double>)> &&kernel)¶
Constructor, takes the quantum kernel with prescribed signature.
-
gradient() = default¶
Empty constructor.
-
template<typename KernelT, typename ArgsMapper>
inline gradient(KernelT &kernel, ArgsMapper &&argsMapper)¶ Constructor, takes a callable with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
template<typename QuantumKernel, typename ...Args>
inline void setArgs(QuantumKernel &kernel, Args&&... args)¶ Take the quantum kernel and concrete arguments for all arguments except the first std::vector<double> argument, which is used for the variational parameters for the gradient. Serialize and save those arguments into this object. (Useful for NVQC.)
-
template<typename QuantumKernel>
inline void setKernel(QuantumKernel &kernel)¶ Set the kernel after the gradient has been constructed. Use of this function requires that the kernel ONLY accept the variational parameters. It cannot have any non-variational parameters.
-
template<typename KernelT, typename = std::enable_if_t<std::is_invocable_v<KernelT, std::vector<double>>>>
inline gradient(KernelT &kernel)¶ Constructor, takes a callable that must have the prescribed call signature (void(std::vector<double>))
-
template<typename QuantumKernel, typename ArgsMapper>
inline gradient(QuantumKernel &&kernel, ArgsMapper &&argsMapper)¶ Constructor, takes the quantum kernel with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
virtual void compute(const std::vector<double> &x, std::vector<double> &dx, const spin_op &h, double funcAtX) = 0¶
Compute the current iterations gradient vector and update the provided vector<double reference (
dx
).
-
virtual std::vector<double> compute(const std::vector<double> &x, const std::function<double(std::vector<double>)> &func, double funcAtX) = 0¶
Compute the gradient vector for the provided objective function,
func
, at the given set of parameters,x
.
-
inline gradient(std::function<void(std::vector<double>)> &&kernel)¶
-
class central_difference : public cudaq::gradient¶
Public Functions
-
inline virtual std::unique_ptr<cudaq::gradient> clone() override¶
Clone the object. Must be implemented by derived classes.
-
inline virtual void compute(const std::vector<double> &x, std::vector<double> &dx, const spin_op &h, double exp_h) override¶
Compute the current iterations gradient vector and update the provided vector<double reference (
dx
).
-
inline virtual std::vector<double> compute(const std::vector<double> &x, const std::function<double(std::vector<double>)> &func, double funcAtX) override¶
Compute the
central_difference
gradient for the arbitrary function,func
, passed in by the user.
-
inline gradient(std::function<void(std::vector<double>)> &&kernel)¶
Constructor, takes the quantum kernel with prescribed signature.
-
gradient() = default¶
Empty constructor.
-
template<typename KernelT, typename ArgsMapper>
inline gradient(KernelT &kernel, ArgsMapper &&argsMapper)¶ Constructor, takes a callable with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
template<typename KernelT, typename = std::enable_if_t<std::is_invocable_v<KernelT, std::vector<double>>>>
inline gradient(KernelT &kernel)¶ Constructor, takes a callable that must have the prescribed call signature (void(std::vector<double>))
-
template<typename QuantumKernel, typename ArgsMapper>
inline gradient(QuantumKernel &&kernel, ArgsMapper &&argsMapper)¶ Constructor, takes the quantum kernel with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
inline virtual std::unique_ptr<cudaq::gradient> clone() override¶
-
class parameter_shift : public cudaq::gradient¶
Public Functions
-
inline virtual std::unique_ptr<cudaq::gradient> clone() override¶
Clone the object. Must be implemented by derived classes.
-
inline virtual void compute(const std::vector<double> &x, std::vector<double> &dx, const spin_op &h, double exp_h) override¶
Compute the current iterations gradient vector and update the provided vector<double reference (
dx
).
-
inline virtual std::vector<double> compute(const std::vector<double> &x, const std::function<double(std::vector<double>)> &func, double funcAtX) override¶
Compute the
parameter_shift
gradient for the arbitrary function,func
, passed in by the user.
-
inline gradient(std::function<void(std::vector<double>)> &&kernel)¶
Constructor, takes the quantum kernel with prescribed signature.
-
gradient() = default¶
Empty constructor.
-
template<typename KernelT, typename ArgsMapper>
inline gradient(KernelT &kernel, ArgsMapper &&argsMapper)¶ Constructor, takes a callable with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
template<typename KernelT, typename = std::enable_if_t<std::is_invocable_v<KernelT, std::vector<double>>>>
inline gradient(KernelT &kernel)¶ Constructor, takes a callable that must have the prescribed call signature (void(std::vector<double>))
-
template<typename QuantumKernel, typename ArgsMapper>
inline gradient(QuantumKernel &&kernel, ArgsMapper &&argsMapper)¶ Constructor, takes the quantum kernel with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
inline virtual std::unique_ptr<cudaq::gradient> clone() override¶
-
class forward_difference : public cudaq::gradient¶
Compute the first order forward difference approximation for the gradient.
Public Functions
-
inline virtual std::unique_ptr<cudaq::gradient> clone() override¶
Clone the object. Must be implemented by derived classes.
-
inline virtual void compute(const std::vector<double> &x, std::vector<double> &dx, const spin_op &h, double funcAtX) override¶
Compute the
forward_difference
gradient.
-
inline virtual std::vector<double> compute(const std::vector<double> &x, const std::function<double(std::vector<double>)> &func, double funcAtX) override¶
Compute the
forward_difference
gradient for the arbitrary function,func
, passed in by the user.
-
inline gradient(std::function<void(std::vector<double>)> &&kernel)¶
Constructor, takes the quantum kernel with prescribed signature.
-
gradient() = default¶
Empty constructor.
-
template<typename KernelT, typename ArgsMapper>
inline gradient(KernelT &kernel, ArgsMapper &&argsMapper)¶ Constructor, takes a callable with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
template<typename KernelT, typename = std::enable_if_t<std::is_invocable_v<KernelT, std::vector<double>>>>
inline gradient(KernelT &kernel)¶ Constructor, takes a callable that must have the prescribed call signature (void(std::vector<double>))
-
template<typename QuantumKernel, typename ArgsMapper>
inline gradient(QuantumKernel &&kernel, ArgsMapper &&argsMapper)¶ Constructor, takes the quantum kernel with non-standard signature the Argument Mapper function object that maps the parameters to concrete arguments for the quantum kernel.
-
inline virtual std::unique_ptr<cudaq::gradient> clone() override¶
Platform¶
-
class QPU : public cudaq::registry::RegisteredType<QPU>¶
A CUDA-Q QPU is an abstraction on the quantum processing unit which executes quantum kernel expressions. The QPU exposes certain information about the QPU being targeting, such as the number of available qubits, the logical ID for this QPU in a set of available QPUs, and its qubit connectivity. The QPU keeps track of an execution queue for enqueuing asynchronous tasks that execute quantum kernel expressions. The QPU also tracks the client-provided execution context to enable quantum kernel related tasks such as sampling and observation.
This type is meant to be subtyped by concrete quantum_platform subtypes.
Subclassed by cudaq::BaseRemoteRESTQPU, cudaq::BaseRemoteSimulatorQPU, cudaq::OrcaRemoteRESTQPU
Public Functions
-
inline QPU()¶
The constructor, initializes the execution queue.
-
inline QPU(std::size_t _qpuId)¶
The constructor, sets the current QPU Id and initializes the execution queue
-
virtual ~QPU() = default¶
The destructor.
-
inline std::thread::id getExecutionThreadId() const¶
Get id of the thread this QPU’s queue executes on.
-
inline std::size_t getNumQubits()¶
Return the number of qubits.
-
inline auto getConnectivity()¶
Return the qubit connectivity.
-
inline virtual bool supportsConditionalFeedback()¶
Return whether this QPU has conditional feedback support.
-
inline virtual bool supportsExplicitMeasurements()¶
Return whether this QPU supports explicit measurements.
-
inline virtual RemoteCapabilities getRemoteCapabilities() const¶
Return the remote capabilities for this platform.
-
inline virtual void setShots(int _nShots)¶
Base class handling of shots is do-nothing, subclasses can handle as they wish
-
virtual void enqueue(QuantumTask &task) = 0¶
Enqueue a quantum task on the asynchronous execution queue.
-
virtual void setExecutionContext(ExecutionContext *context) = 0¶
Set the execution context, meant for subtype specification.
-
virtual void resetExecutionContext() = 0¶
Reset the execution context, meant for subtype specification.
-
virtual KernelThunkResultType launchKernel(const std::string &name, KernelThunkType kernelFunc, void *args, std::uint64_t, std::uint64_t, const std::vector<void*> &rawArgs) = 0¶
Launch the kernel with given name (to extract its Quake representation). The raw function pointer is also provided, as are the runtime arguments, as a struct-packed void pointer and its corresponding size.
-
inline virtual void launchKernel(const std::string &name, const std::vector<void*> &rawArgs)¶
Launch the kernel with given name and argument arrays.
-
inline virtual void launchSerializedCodeExecution(const std::string &name, cudaq::SerializedCodeExecutionContext &serializeCodeExecutionObject)¶
Launch serialized code for remote execution. Subtypes that support this should override this function.
-
inline QPU()¶
-
class BaseRemoteRESTQPU : public cudaq::QPU¶
Subclassed by cudaq::FermioniqBaseQPU, cudaq::PasqalBaseQPU, cudaq::QuEraBaseQPU
-
class BaseRemoteSimulatorQPU : public cudaq::QPU¶
Subclassed by cudaq::BaseNvcfSimulatorQPU
-
class BaseNvcfSimulatorQPU : public cudaq::BaseRemoteSimulatorQPU¶
Implementation of base QPU subtype that submits simulation request to NVCF.
-
class FermioniqBaseQPU : public cudaq::BaseRemoteRESTQPU¶
The
FermioniqBaseQPU
is a QPU that allows users to.
-
class OrcaRemoteRESTQPU : public cudaq::QPU¶
The OrcaRemoteRESTQPU is a subtype of QPU that enables the execution of CUDA-Q kernels on remotely hosted quantum computing services via a REST Client / Server interaction. This type is meant to be general enough to support any remotely hosted service. Moreover, this QPU handles launching kernels under the Execution Context that includes sampling via synchronous client invocations.
-
class PasqalBaseQPU : public cudaq::BaseRemoteRESTQPU¶
The
PasqalBaseQPU
is a QPU that allows users to submit kernels to the Pasqal machine.
-
class QuEraBaseQPU : public cudaq::BaseRemoteRESTQPU¶
The
QuEraBaseQPU
is a QPU that allows users to.
-
class quantum_platform¶
The quantum_platform corresponds to a specific quantum architecture. The quantum_platform exposes a public API for programmers to query specific information about the targeted QPU(s) (e.g. number of qubits, qubit connectivity, etc.). This type is meant to be subclassed for concrete realizations of quantum platforms, which are intended to populate this platformQPUs member of this base class.
Public Functions
-
std::optional<QubitConnectivity> connectivity()¶
Fetch the connectivity info.
-
inline virtual bool supports_task_distribution() const¶
Return true if this platform exposes multiple QPUs and supports parallel distribution of quantum tasks.
-
std::size_t get_num_qubits(std::size_t qpu_id)¶
Get the number of qubits for the QPU with ID qpu_id.
-
inline std::optional<int> get_shots()¶
Getter for the shots. This will be deprecated once
set_shots
andclear_shots
are removed.
-
inline virtual void set_shots(int numShots)¶
Setter for the shots.
-
inline virtual void clear_shots()¶
Reset shots.
-
void set_exec_ctx(cudaq::ExecutionContext *ctx, std::size_t qpu_id = 0)¶
Specify the execution context for this platform.
-
inline ExecutionContext *get_exec_ctx() const¶
Return the current execution context.
-
void reset_exec_ctx(std::size_t qpu_id = 0)¶
Reset the execution context for this platform.
-
inline std::size_t num_qpus() const¶
Get the number of QPUs available with this platform.
-
bool is_simulator(const std::size_t qpu_id = 0) const¶
Return whether this platform is simulating the architecture.
-
bool supports_conditional_feedback(const std::size_t qpu_id = 0) const¶
Return whether the QPU has conditional feedback support.
-
bool supports_explicit_measurements(const std::size_t qpu_id = 0) const¶
Return whether the QPU supports explicit measurements.
-
inline std::string name() const¶
The name of the platform, which also corresponds to the name of the platform file.
-
bool is_emulated(const std::size_t qpuId = 0) const¶
-
void set_noise(const noise_model *model)¶
Set the noise model for future invocations of quantum kernels.
-
const noise_model *get_noise()¶
Return the current noise model or
nullptr
if none set.
-
RemoteCapabilities get_remote_capabilities(const std::size_t qpuId = 0) const¶
Get the remote capabilities (only applicable for remote platforms)
-
void reset_noise()¶
Turn off any noise models.
-
std::future<sample_result> enqueueAsyncTask(const std::size_t qpu_id, KernelExecutionTask &t)¶
Enqueue an asynchronous sampling task.
-
void enqueueAsyncTask(const std::size_t qpu_id, std::function<void()> &f)¶
Enqueue a general task that runs on the specified QPU.
-
void launchVQE(const std::string kernelName, const void *kernelArgs, cudaq::gradient *gradient, const cudaq::spin_op &H, cudaq::optimizer &optimizer, const int n_params, const std::size_t shots)¶
Launch a VQE operation on the platform.
-
inline virtual void setTargetBackend(const std::string &name)¶
Set the target backend, by default do nothing, let subclasses override.
- Parameters:
name –
-
virtual void onRandomSeedSet(std::size_t seed)¶
Called by the runtime to notify that a new random seed value is set.
-
void resetLogStream()¶
Turn off any custom logging stream.
-
std::ostream *getLogStream()¶
Get the stream for info logging.
-
void setLogStream(std::ostream &logStream)¶
Set the info logging stream.
Public Static Functions
-
static std::vector<std::string> list_platforms()¶
List all available platforms.
-
std::optional<QubitConnectivity> connectivity()¶
-
struct RemoteCapabilities¶
A structure of boolean fields to indicate whether a given remote server has specific capabilities.
Public Functions
-
inline RemoteCapabilities(bool initValue)¶
Constructor that broadcasts
initValue
to all fields.
Public Members
-
bool stateOverlap = false¶
True if the remote can perform state overlap operations.
-
bool serializedCodeExec = false¶
True if the remote can perform serialized code execution (raw Python commands).
-
bool vqe = false¶
True if the remote can perform an entire VQE operation without and back-and-forth client/server communications.
-
bool isRemoteSimulator = false¶
True if execution is performed on a remote simulator - i.e. IR generation (including synthesis) and execution are performed in different processes.
-
inline RemoteCapabilities(bool initValue)¶
-
class SerializedCodeExecutionContext¶
The SerializedCodeExecutionContext is an abstraction to indicate how a serialized code should be executed.
-
using cudaq::QuantumTask = std::function<void()>¶
The QuantumTask is ultimately what gets added to the execution queue. It is meant to wrap any Sampling or Observe task with an appropriate std::promise instance being provided and set.
-
using cudaq::QubitEdge = std::pair<std::size_t, std::size_t>¶
Typedefs for defining the connectivity structure of a QPU.
-
using cudaq::KernelExecutionTask = std::function<sample_result()>¶
A sampling tasks takes no input arguments and returns a sample_result instance.
-
struct KernelThunkResultType¶
A kernel may return results dynamically if the size of the result is not a constant at compile-time.
-
using cudaq::KernelThunkType = KernelThunkResultType (*)(void*, bool)¶
The universal signature of a kernel thunk.
Utilities¶
Namespaces¶
-
namespace cudaq¶
-
void cudaq::set_random_seed(std::size_t seed)¶
Set a seed for any random number generators used in backend simulations.
-
void cudaq::set_noise(const cudaq::noise_model &model)¶
Set a custom noise model for simulation. The caller must also call
cudaq::unset_noise
beforemodel
gets deallocated or goes out of scope.
-
namespace details¶
-
namespace registry¶
-
namespace mpi¶
-
void cudaq::mpi::initialize()¶
Initialize MPI if available. This function is a no-op if there CUDA-Q has not been built against MPI.
-
void cudaq::mpi::initialize(int argc, char **argv)¶
Initialize MPI if available. This function is a no-op if there CUDA-Q has not been built against MPI. Takes program arguments as input.
-
void cudaq::mpi::finalize()¶
Finalize MPI. This function is a no-op if there CUDA-Q has not been built against MPI.
-
void cudaq::mpi::all_gather(std::vector<double> &global, const std::vector<double> &local)¶
Gather all vector data (floating point numbers) locally into the provided global vector.
Global vector must be sized to fit all vector elements coming from individual ranks.
-
void cudaq::mpi::all_gather(std::vector<int> &global, const std::vector<int> &local)¶
Gather all vector data (integers) locally into the provided global vector.
Global vector must be sized to fit all vector elements coming from individual ranks.
-
template<typename T, typename BinaryFunction>
T cudaq::mpi::all_reduce(const T &localValue, const BinaryFunction &function)¶ Reduce all values across ranks with the specified binary function.
-
void cudaq::mpi::broadcast(std::vector<double> &data, int rootRank)¶
Broadcast a vector from a process (rootRank) to all other processes.
-
void cudaq::mpi::broadcast(std::string &data, int rootRank)¶
Broadcast a string from a process (rootRank) to all other processes.
-
namespace orca¶
-
cudaq::sample_result cudaq::orca::sample(std::vector<std::size_t> &input_state, std::vector<std::size_t> &loop_lengths, std::vector<double> &bs_angles, int n_samples = 10000, std::size_t qpu_id = 0)¶
-
cudaq::sample_result cudaq::orca::sample(std::vector<std::size_t> &input_state, std::vector<std::size_t> &loop_lengths, std::vector<double> &bs_angles, std::vector<double> &ps_angles, int n_samples = 10000, std::size_t qpu_id = 0)¶
Implementation of the sample method of the cudaq::orca namespace.
-
async_sample_result cudaq::orca::sample_async(std::vector<std::size_t> &input_state, std::vector<std::size_t> &loop_lengths, std::vector<double> &bs_angles, int n_samples = 10000, std::size_t qpu_id = 0)¶
-
async_sample_result cudaq::orca::sample_async(std::vector<std::size_t> &input_state, std::vector<std::size_t> &loop_lengths, std::vector<double> &bs_angles, std::vector<double> &ps_angles, int n_samples = 10000, std::size_t qpu_id = 0)¶