## Library SpinQit provides useful APIs for developers to use in their own quantum programs. Users can define custom quantum gates, build new quantum algorithms, and invoke existing algorithms. This section introduces SpinQit's APIs. ### GateBuilders A gate builder is used to define a custom gate. The developer needs to call the to_gate method of a builder to get the gate. SpinQit also provides several specific gate builders:
Build a gate which applies the same subgate on multiple qubits.
Methods
Create a RepeatBuilder instance.
g – Gate, the gate to repeat
repeat – int, how many qubits to apply g
param_lambda - float or Callable, optional gate parameters; None by default
A RepeatBuilder instance
h4 = RepeatBuilder(H, 4).to_gate()
Build the inverse gate of a given gate.
Methods
Create an InverseBuilder instance.
gate – Gate, the gate to invert
A GateBuilder instance
x_inv = InverseBuilder(X).to_gate()
Build a multi-controlled phase gate or a multi-controlled Rz gate.
Methods
Create a MultiControlPhaseGateBuilder instance.
ctrl_qubit_num – int, the number of control qubits. Note that the total number of qubits for the generated gate is the number of control qubits plus one.
A GateBuilder instance
c3p = MultiControlPhaseGateBuilder(3).to_gate()
Build a Z-basis parametric Ising coupling gate.
Methods
Create a Z_IsingGateBuilder instance.
qubit_num – int, the number of qubits on which the gate acts
name - str, name of the gate, 'Z_Ising' by default
A GateBuilder instance
rzz = Z_IsingGateBuilder(2).to_gate()
Build an X-basis parametric Ising coupling gate.
Methods
Create a X_IsingGateBuilder instance.
qubit_num – int, the number of qubits on which the gate acts
name - str, name of the gate, 'X_Ising' by default
A GateBuilder instance
rxx = X_IsingGateBuilder(2).to_gate()
Build a Y-basis parametric Ising coupling gate.
Methods
Create a Y_IsingGateBuilder instance.
qubit_num – int, the number of qubits on which the gate acts
name - str, name of the gate, 'Y_Ising' by default
A GateBuilder instance
ryy = Y_IsingGateBuilder(2).to_gate()
Build a multi-controlled single-qubit gate.
Methods
Create a MultiControlledGateBuilder instance.
ctrl_num – int, the number of control qubits
gate - Gate, numpy.ndarray, or list, the single-qubit gate applied to the target qubit; it can be a Gate instance in SpinQit or a unitary matrix represented by an ndarray or list
params – List, the parameters for the Gate instance, None by default
A GateBuilder instance
mcz = MultiControlledGateBuilder(3, Z)
Build a uniformly controlled single-qubit gate.
Methods
Create a UniformlyControlledGateBuilder instance.
ctrl_num – int, the number of control qubits
gate - Gate, numpy.ndarray, or list, the single-qubit gate applied to the target qubit; it can be a Gate instance in SpinQit or a unitary matrix represented by an ndarray or list
params – List, the parameters for the Gate instance, None by default
up_to_diag – bool, whether to implement the uniformly controlled gate up to diagonal gates; False by default
add_phase – bool, whether to add the global phase, True by default
A GateBuilder instance
ucz = UniformlyControlledGateBuilder(3, Rz, [np.pi/2])
gate - Gate, the base gate
exponent - int or float, the exponent
qubits - List, where to apply the power of gate
params - List, optional parameters of gate, and the default value is []
control - bool, whether to generate the controlled power gate, and the default value is False
control_bit - int, the control qubit; defaults to None
The instructions that represent the power of a given gate.
Generates the instructions for amplitude amplification.
Methods
Create an AmplitudeAmplification instance.
flip - Gate, the gate to flip the phase of the target
flip_qubits - List, the qubits to apply the flip gate
flip_params - List, the optional parameters in the flip gate
state_operator - Gate, the gate to prepare the state that represents the search space, by default using uniform superposition
state_qubits - List, the qubits to prepare the state
state_params - List, the optional parameters in the state operator gate
reflection_qubits - List, the qubits to apply the reflect operation
An AmplitudeAmplification instance
Return the instructions for amplitude amplification.
A list of instructions for amplitude amplification
We provide an example of the Grover algorithm that uses amplitude amplification in example/grover_example.py.
Generates a gate for quantum Fourier transform or inverse quantum Fourier transform.
Methods
Create a QFT instance.
qubit_num - int, the number of qubits to apply QFT/inverse QFT
A QFT instance
Build a gate for QFT.
A gate to do quantum Fourier transform
Build a gate for inverse QFT.
A gate to do inverse quantum Fourier transform
Generates instructions that estimate the eigenvalue of a given gate corresponding to a specific eigenvector.
Methods
Create a PhaseEstimation instance.
unitary - Gate, the gate to apply quantum phase estimation
state_qubits - List, the qubits that encode the eigenvector
output_qubits - List, the qubits that output the estimation result
params - List, optional parameters of the input gate, and [] by default
A PhaseEstimation instance
Generate instructions for QPE.
Instructions to do quantum phase estimation
Generate instructions for inverse QPE.
Instructions to do inverse quantum phase estimation
Harrow-Hassidim-Lloyd (HHL) quantum algorithm is used to solve a system of linear equations.
Methods
Initialize an HHL solver.
mat_A - numpy.ndarray, the coefficient matrix
vec_b - numpy.ndarray, the right side constant vector
An HHL instance for a specific system of linear equations
Run the solver.
backend - BaseBackend, the backend instance to execute the algorithm
config - Config, the configuration for the backend
None
We provide an example of HHL in example/hhl_example.py
Get the probabilities after running the solver.
A dictionary of the probabilities of different measurements from the solver
Get the state vector after running the solver, working only with simulator backends.
A dictionary of the probabilities of different measurements from the solver
VQE is short for variational quantum eigensolver, which finds the minimum eigenvalue of a Hermitian matrix H. VQE uses a parameterized ansatz to implement the variational principle. When H describes the Hamiltonian of a system, VQE can obtain the ground state energy of the Hamiltonian.
Methods
Initialize a VQE solver.
hamiltonian - scipy.sparse.csr_matrix or List, the input Hamiltonian which can be a matrix or described by its Pauli decomposition, i.e., a list of (Pauli string, coefficient) pairs
ansatz - Circuit, the ansatz circuit, and a hardware efficient ansatz is used when this parameter is None
optimizer - Optimizer, the optimizer used to optimize the variational parameters
params - array-like or tuple, the initial parameters or the parameter shape, random parameters are created for the default ansatz when None is passed
depth - int, how many times to repeat the default ansatz
A VQE instance
Run the solver.
mode - str, the backend mode, 'spinq', 'torch', 'nmr', corresponding to the basic simulator, the pytorch simulator and the NMR machine respectively
grad_method - str, the method to calculate the gradients, 'param_shift', 'adjoint_differentiation' and 'backprop'
A list of loss values
We provide an example of VQE in example/vqe_h2_example.py
Quantum Approximate Optimization Algorithm (QAOA) is a variational algorithm to solve combinatorial optimization problems.
Methods
Initialize a QAOA solver.
problem - scipy.sparse.csr_matrix or List, the problem Hamiltonian which can be a matrix, or described by its Pauli decomposition, i.e., a list of (Pauli string, coefficient) pairs
optimizer - Optimizer, the optimizer used to optimize the variational parameters
depth - int, how many times to repeat the problem ansatz and the mixer ansatz
problem_ansatz - Gate, a custom gate for the problem ansatz, and a default ansatz is built based on the problem parameter
mixer_ansatz - Gate, a custom gate for the mixer ansatz, and a default Rx ansatz is used when this parameter is None
A QAOA instance
Run the solver.
mode - str, the backend mode, 'spinq' or 'torch', corresponding to the basic simulator and the pytorch simulator respectively
grad_method - str, the method to calculate the gradients, 'param_shift' and 'adjoint_differentiation' for the 'spinq' mode and 'backprop' for the 'torch' mode
A list of loss values
We provide an example of QAOA in example/qaoa_maxcut_example.py
Get the measurements of the final circuit.
Execution Result after Optimization
The Grover algorithm is designed to find a solution to an oracle function, while the quantum counting algorithm finds out how many of these solutions there are. This algorithm is a quantum phase estimation of the Grover operator.
Methods
Initialize a QuantumCounting instance for a specific problem.
counting_num - int, the number of qubits to read out the count
searching_num - int, the number of qubits to apply the oracle
prep - Gate, the gate to prepare the states
oracle - Gate, the oracle to count
prep_params - List, [] by default, the optional parameters in the prep gate
oracle_params - List, [] by default, the optional parameters in the oracle gate
A QuantumCounting instance
Solve the quantum counting problem.
backend - BaseBackend, the backend instance to execute the algorithm
config - Config, the configuration for the backend
The count of targets
We provide an example of quantum counting in example/quantum_counting_example.py
The QSearching algorithm searches for the index of the maximum or minimum value in an array.
Methods
Initialize a QSearching instance.
objective - str, 'max' or 'min'; 'max' by default
backend_mode - str, the backend mode passed to check_backend_and_config; 'spinq' by default
seed - None, int, float, str, bytes, or bytearray, the random seed used in the algorithm
**kwargs - additional keyword arguments passed to the backend and configuration factory
A QSearching instance
Search for the maximum or minimum value in the dataset and return its index. The dataset size must be a power of two.
dataset - array-like, the input array to search; its length must be a power of two
show - bool, whether to print the result; True by default
The index of the maximum or minimum value
We provide an example of quantum searching in example/search_max_min.py.
Given an operator A that A|0> = √1-a |Ψ0> + √a |Ψ1>, this class estimates the amplitude a of the state |Ψ1>.
Methods
Initialize an AmplitudeEstimation instance.
eval_num - int, the number of qubits used for estimation which determines the estimation precision
A - Gate, the target gate to estimate
params - float or list, optional parameters required by A, None by default
backend_mode - str, the backend to execute the quantum circuit, one of 'spinq' (default), 'torch', 'qasm', 'nmr', and 'cloud'
**kwargs - Any, configurations for the backend
An AmplitudeEstimation instance
Execute the estimation algorithm.
The estimation of the amplitude
This class implements the amplitude estimation algorithm based on maximum likelihood.
Methods
Initialize a MaximumLikelihoodAmplitudeEstimation instance.
circuit_num - int,
A - Gate, the target gate to estimate
alpha - float, 0.05 by default,
params - float or list, optional parameters required by A, None by default
backend_mode - str, the backend to execute the quantum circuit, one of 'spinq' (default), 'torch', 'qasm', 'nmr', and 'cloud'
**kwargs - Any, configurations for the backend
A MaximumLikelihoodAmplitudeEstimation instance
Execute the estimation algorithm.
The estimation of the amplitude
This class implements a coined quantum walk.
Methods
Initialize a CoinedQuantumWalk instance.
state_qubit_num - int, the number of qubits used for the position state
coin_qubit_num - int, the number of qubits used for the coin
init_operator - Gate, the operator to initialize all the qubits
coin_operator - Gate, the operator that randomly determines how to move next
shift_operator - Gate, the operator that updates the position state
backend_mode - str, the backend to execute the quantum circuit, one of 'spinq' (default), 'torch', 'qasm', 'nmr', and 'cloud'
**kwargs - Any, configurations for the backend
A CoinedQuantumWalk instance
Execute the quantum walk using the coin.
steps - int, the number of steps to walk
The probabilities of positions after the walk
coin_qubit_num – int, the number of qubits used for the coin
A composite Gate as a Grover coin
QSVC is a classifier based on quantum support vector machine. Both quantum kernel and projected quantum kernel methods are available for selection.
Methods
Create a QSVC instance with a custom quantum featuremap or basic information. Either featuremap or qubit_num must be specified.
featuremap – Callable, the function defining the quantum circuit and decorated by to_qlayer
use_projected - bool, whether to use projected quantum kernel or quantum kernel method
qubit_num - int, the number of qubits in the quantum kernel which is None when featuremap is given
measure - MeasureOp, defined by functions such as expval (for projected quantum kernel) and probs (for quantum kernel), and used when featuremap is None
backend_mode - str, the backend to execute the quantum circuit, one of 'spinq', 'torch', 'qasm', 'nmr', and 'cloud'
**kwargs - Any, configurations for the backend
A QSVC instance
Fit the SVM model according to the given training data in the same way as the fit function of sklearn.svm.SVC.
X_train – numpy.ndarray, the training samples
y_train – numpy.ndarray, labels for class membership of each sample
Fitted SVM estimator.
Perform classification on samples in X.
X_test – numpy.ndarray, the input data
Class labels for samples in X_test
This class extends torch.autograd.Function and defines forward and backward for quantum computing. The only special parameter is qlayer which must be given to the forward function.
Methods
ctx - torch.autograd.function.FunctionCtx, context between forward and backward
kwargs – dict, qlayer is passed through this dict
*params – torch.Tensor, parameters in the quantum circuit
ctx - torch.autograd.function.FunctionCtx, context between forward and backward
grad_output – torch.Tensor, the gradient w.r.t the forward output
This class extends torch.nn.Module and defines a quantum module for PyTorch. The module employs the evaluation output of a single quantum circuit and an optional bias parameter. Users needing additional post-processing aside from the bias will have to define their own quantum module built upon QuantumFunction.
Methods
Create a QuantumModule that can be used in a PyTorch network for hybrid classical-quantum machine learning.
quantum_layer – QLayer, the interface wrapping circuit and execution configuration
weight_shape - tuple or torch.Size, the shape of the parameter tensor
bias - torch.nn.Parameter, the optional parameter to add to the evaluation result
A QuantumModule instance
state - torch.Tensor, the training or test data
qlayer – QLayer, the interface wrapping circuit and execution configuration
A function returning the forward result and gradient function
This class extends tensorflow.keras.layers.Layer and defines a quantum layer for TensorFlow. The module employs the evaluation output of a quantum circuit and an optional bias parameter. Users needing extra post-processing aside from the bias will have to define their own quantum layer based on get_quantum_func.
Methods
Create a QuantumLayer that can be used in a TensorFlow network for hybrid classical-quantum machine learning.
quantum_layer – QLayer, the interface wrapping circuit and execution configuration
weight_shape - tuple or TensorShape, the shape of the parameter tensor
bias - tensorflow.Variable, None by default, the optional parameter to add to the evaluation result
A QuantumLayer instance
state - tensorflow.Variable, the training or test data
This class extends paddle.autograd.PyLayer and defines forward and backward for quantum computing. The only special parameter is qlayer which must be given to the forward function.
Methods
ctx - paddle.autograd. PyLayerContext, context between forward and backward
kwargs – dict, qlayer is passed through this dict
*params – paddle.Tensor, parameters in the quantum circuit
ctx - paddle.autograd. PyLayerContext, context between forward and backward
dy – paddle.Tensor, the gradient w.r.t the forward output
vector – numpy.ndarray, the input classical vector
qubits - List, the qubits to encode the input vector
The instructions prepare quantum states to encode the given vector.
vector – numpy.ndarray or PlaceHolder, the input classical vector
qubits - List, the qubits to encode the input vector
depth - int, how many times to repeat the encoding gates, 1 by default
rotate_gate - str, the rotation gate 'rx', 'ry' or 'rz' to use, 'ry' by default
The instructions for the rotation gates.
Encodes classical information $x$ into $ (U_Z(x)H^{\otimes n})^d \vert 0^n\rangle $. Please refer to Havlíček, Vojtěch, et al. "Supervised learning with quantum-enhanced feature spaces." for details.
vector – numpy.ndarray or PlaceHolder, the input classical vector
qubits - List, the qubits to encode the input vector
depth - int, 1 by default, how many times to repeat the basic IQP circuit
ring_pattern - bool, False by default, whether to apply a rzz gate to the first and last qubits
The instructions for the instantaneous quantum polynomial circuit
vector – numpy.ndarray, the input classical binary vector
qubits - List, the qubits to encode the input vector
The instructions prepare quantum states to encode the given vector.
An objective function calculating the state fidelity.
Methods
Calculate the fidelity between a state and a target state.
state – list or torch.Tensor like, the input state vector
target_state – list or torch.Tensor like, the target state vector
The fidelity value
An objective function calculating the Von Neumann Entropy.
Methods
Create a VNEntropy instance.
log_base – float, log(log_base) is used as the dividend in the computation of the entropy
A VNEntropy instance
Calculate the Von Neumann entropy of a state.
state – list or torch.Tensor like, the input state vector
indices – list, the indices of subsystems to keep in the output, which essentially represent the qubits
The Von Neumann entropy
An objective function calculating the mutual information.
Methods
Create a MutualInfo instance.
log_base – float, log(log_base) is used as the dividend in the computation of the VN entropies
A MutualInfo instance
Calculate the mutual information between two subsystems.
state – list or torch.Tensor like, the input state vector
indices0 – list, the indices of the first subsystem
indices1 – list, the indices of the second subsystem
The mutual information between two subsystems
An objective function calculating the relative entropy.
Methods
Create a RelativeEntropy instance.
log_base – float, log(log_base) is used as the dividend in the computation of the VN entropies
A RelativeEntropy instance
Calculate the relative entropy between two states.
state0 – list or torch.Tensor like, the first input state vector
state1 – list or torch.Tensor like, the second input state vector
The relative entropy
Native implementation of ADAM optimizer in SpinQit.
Methods
Create an ADAM optimizer instance.
maxiter – int, maximum number of iterations, 1000 by default
tolerance – float, tolerance for termination, 1e-4 by default
learning_rate – float, the learning rate, 0.01 by default
beta1 – float, decay rate for the first moment of the gradient, 0.9 by default
beta2 – float, decay rate for the second moment of the gradient, 0.99 by default
noise_factor – float, noise factor which >= 0, 1e-8 by default
verbose – bool, whether to show optimization details, True by default
An ADAM instance
Optimize the objective function.
qlayer – QLayer, the interface wrapping circuit and execution configuration
*params - Parameter, parameters used in the quantum circuit
The list of loss values
Native implementation of gradient descent optimizer in SpinQit.
Methods
Create a GradientDescent optimizer instance.
maxiter – int, maximum number of iterations, 1000 by default
tolerance – float, tolerance for termination, 1e-6 by default
learning_rate – float, the learning rate, 0.01 by default
verbose – bool, whether to show optimization details, True by default
A GradientDescent instance
Optimize the objective function.
qlayer – QLayer, the interface wrapping circuit and execution configuration
*params - Parameter, parameters used in the quantum circuit
The list of loss values
Implementation of quantum natural gradient optimizer in SpinQit
Methods
Create a QuantumNaturalGradient optimizer instance.
maxiter – int, maximum number of iterations, 1000 by default
tolerance – float, tolerance for termination, 1e-6 by default
learning_rate – float, the learning rate, 0.01 by default
verbose – bool, whether to show optimization details, True by default
A QuantumNaturalGradient instance
Optimize the objective function.
qlayer – Qlayer, the interface wrapping circuit and execution configuration
*params - Parameter, parameters used in the quantum circuit
The list of loss values
Interface to use optimizers in PyTorch, including NAdam, Adam, SGD, AdamW, Adagrad
Methods
Create a TorchOptimizer instance to call optimizers in PyTorch.
maxiter – int, maximum number of iterations, 1000 by default
tolerance – float, tolerance for termination, 1e-6 by default
learning_rate – float, the learning rate, 0.01 by default
verbose – bool, whether to show optimization details, True by default
optim_type – str, 'NAdam', 'Adam', 'SGD', 'AdamW', or 'Adagrad', and the default type is 'NAdam'
kwargs - dict, other parameters used by PyTorch optimizers
An interface instance that calls the optimizers in PyTorch
Optimize the objective function.
qlayer – Qlayer, the interface wrapping circuit and execution configuration
*params - Parameter, parameters used in the quantum circuit
The list of loss values
Interface to call optimizers in SciPy, specifically, "Nelder-Mead" and "COBYLA"
Methods
Create a ScipyOptimizer instance to call optimizers in SciPy.
maxiter – int, maximum number of iterations, 10000 by default
tolerance – float, tolerance for termination, 1e-4
verbose – bool, whether to show optimization details, False by default
method – str, 'Nelder-Mead' or 'COBYLA', by default 'COBYLA'
An interface instance that calls the optimizers in SciPy
Optimize the objective function.
fn – Qlayer, the interface wrapping circuit and execution configuration
*params - Parameter, parameters used in the quantum circuit
The list of loss values
Interface to use the minimizeSPSA optimizer from noisyopt.
Methods
Create a SPSAOptimizer instance to call the minimizeSPSA optimizer.
maxiter – int, maximum number of iterations, 100 by default
verbose – bool, whether to show optimization details, False by default
a - float, scaling parameter for step size, 1.0 by default
c - float, scaling parameter for evaluation step size, 1.0 by default
An interface instance that calls the minimizeSPSA optimizer
Optimize the objective function.
qlayer – Qlayer, the interface wrapping circuit and execution configuration
*params - Parameter, parameters used in the quantum circuit
The list of loss values
A solver to solve the satisfaction problem using Grover's algorithm.
Methods
Create a SATSolver instance for a specific satisfaction problem.
expr – str or sympy.logic.boolalg.And, the expression that represents the satisfaction problem to solve
An instance of SATSolver
Solve the satisfaction on the given backend.
backend_mode - str, the backend to execute the quantum circuit, one of 'spinq', 'torch', 'qasm', 'nmr', and 'cloud'
**kwargs - Any, configurations for the backend
The assignment satisfying the constraints
A solver to solve the traveling salesman problem using VQE algorithm.
Methods
Create a TSPSolver instance for a specific graph.
vertex_num – int, the number of vertices
weighted_adjacency – list or numpy.ndarray, the weighted adjacency matrix in which weighted_adjacency[i][j] is the weight of the edge from i to j
penalty – float, a parameter required in the algorithm whose value must be larger than the maximum weight
An instance of TSPSolver
Solve the TSP problem with specific configurations.
iterations - int, the number of maximum iterations
backend_mode - str, the backend to execute the quantum circuit, 'spinq' or 'torch'
grad_method - str, the gradient method used in VQE
learning_rate = float, 0.1 by default, the learning rate used in the optimizer
The visiting order of vertices