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 the APIs in SpinQit.

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:

class spinqit.model.RepeatBuilder

Build a gate which applies the same subgate on multiple qubits.

Methods

__init__ (g, repeat, param_lambda)

Create a RepeatBuilder instance.

Parameters

g – Gate, the gate to repeat

repeat – int, how many qubits to apply g

param_lambda - float or Callable, optional parameters of gate, and None by default

Returns

A GateBuilder instance

Example

h4 = RepeatBuilder(H, 4).to_gate()

class spinqit.model.InverseBuilder

Build the inverse gate of a given gate.

Methods

__init__ (gate)

Create a InverseBuilder instance.

Parameters

gate – Gate, the gate to inverse

Returns

A GateBuilder instance

Example

x_inv = InverseBuilder(X).to_gate()

class spinqit.model.MultiControlPhaseGateBuilder

Build a multi-controlled phase gate or a multi-controlled Rz gate.

Methods

__init__ (ctrl_qubit_num)

Create a MultiControlPhaseGateBuilder instance.

Parameters

ctrl_qubit_num – int, the number of control qubits. Please notice that the total number of qubits for the generated gate is the number of control qubits plus one.

Returns

A GateBuilder instance

Example

c3p = MultiControlPhaseGateBuilder(3).to_gate()

class spinqit.model.Z_IsingGateBuilder

Build a Z-basis parameteric Ising coupling gate.

Methods

__init__ (qubit_num, name)

Create a Z_IsingGateBuilder instance.

Parameters

qubit_num – int, the number of qubits interacted

name - str, name of the gate, 'Z_Ising' by default

Returns

A GateBuilder instance

Example

rzz = Z_IsingGateBuilder(2).to_gate()

class spinqit.model.X_IsingGateBuilder

Build a X-basis parameteric Ising coupling gate.

Methods

__init__ (qubit_num, name)

Create a X_IsingGateBuilder instance.

Parameters

qubit_num – int, the number of qubits interacted

name - str, name of the gate, 'X_Ising' by default

Returns

A GateBuilder instance

Example

rxx = X_IsingGateBuilder(2).to_gate()

class spinqit.model.Y_IsingGateBuilder

Build a Y-basis parameteric Ising coupling gate.

Methods

__init__ (qubit_num, name)

Create a Y_IsingGateBuilder instance.

Parameters

qubit_num – int, the number of qubits interacted

name - str, name of the gate, 'Y_Ising' by default

Returns

A GateBuilder instance

Example

ryy = Y_IsingGateBuilder(2).to_gate()

class spinqit.primitive.MultiControlledGateBuilder

Build a multi-controlled single-qubit gate.

Methods

__init__ (ctrl_num, gate, params)

Create a MultiControlledGateBuilder instance.

Parameters

ctrl_num – int, the number of control qubits

gate - Gate, numpy.ndarray, or list, the single-qubit gate applied on the target qubit which could be a Gate instance in SpinQit or a unitary matrix of ndarray or list type

params – List, the parameters for the Gate instance, None by default

Returns

A GateBuilder instance

Example

mcz = MultiControlledGateBuilder(3, Z)

class spinqit.primitive.UniformlyControlledGateBuilder

Build a uniformly controlled single-qubit gate.

Methods

__init__ (ctrl_num, gate, params, up_to_diag, add_phase)

Create a UniformlyControlledGateBuilder instance.

Parameters

ctrl_num – int, the number of control qubits

gate - Gate, numpy.ndarray, or list, the single-qubit gate applied on the target qubit which could be a Gate instance in SpinQit or a unitary matrix of ndarray or list type

params – List, the parameters for the Gate instance, None by default

up_to_diag – bool, whether to implement the uniformly controlled gate up to diagnoal gates, False by default

add_phase – bool, whether to add the global phase, True by default

Returns

A GateBuilder instance

Example

ucz = UniformlyControlledGateBuilder(3, Rz, [np.pi/2])

Primitives

The primitives in this section are subroutines used frequently in quantum programming. These primitives generate instructions or a composite gate to finish the quantum operations. Before generating the instructions, a Circuit instance must be created and qubits must be allocated.

spinqit.primitive.generate_power_gate (gate, exponent, qubits, params, control, control_bit)

Generates the instructions that represent the power of a given gate. The power of the argument “gate” is decomposed to a group of subgates in this function. When “control” is True, the instructions represent the controlled power gate and the argument “control_bit” must be set.

Parameters

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, by default it is None

Returns

The instructions that represent the power of a given gate.

class spinqit.primitive.AmplitudeAmplification

Generates the instructions for amplitude amplification.

Methods

__init__ (flip, flip_qubits, flip_params, state_operator, state_qubits, state_params, reflection_qubits)

Create an AmplitudeAmplification instance.

Parameters

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

Returns

An AmplitudeAmplification instance

build ( )

Return the instructions for amplitude amplification.

Returns

A list of instructions for amplitude amplification

Example

We provide an example of the Grover algorithm that uses amplitude amplification in example/grover_example.py.

class spinqit.primitive.QFT

Generates a gate for quantum Fourier transform or inverse quantum Fourier transform.

Methods

__init__ (qubit_num)

Create a QFT instance.

Parameters

qubit_num - int, the number of qubits to apply QFT/inverse QFT

Returns

A QFT instance

build ( )

Build a gate for QFT.

Returns

A gate to do quantum Fourier transform

inverse ( )

Build a gate for inverse QFT.

Returns

A gate to do inverse quantum Fourier transform

class spinqit.primitive.PhaseEstimation

Generates instructions that estimate the eigenvalue of a given gate corresponding to a specific eigenvector.

Methods

__init__ (unitary, state_qubits, output_qubits, params)

Create a PhaseEstimation instance.

Parameters

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

Returns

A PhaseEstimation instance

build ( )

Generate instructions for QPE.

Returns

Instructions to do quantum phase estimation

inverse ( )

Generate instructions for inverse QPE.

Returns

Instructions to do inverse quantum phase estimation

Algorithms

SpinQit provides APIs for multiple quantum algorithms so that users can run them directly. We provide example codes to show how to use these APIs.

class spinqit.algorithm.HHL

Harrow-Hassidim-Lloyd (HHL) quantum algorithm is used to solve a system of linear equations.

Methods

__init__ (mat_A, vec_b)

Initialize an HHL solver.

Parameters

mat_A - numpy.ndarray, the coefficient matrix

vec_b - numpy.ndarray, the right side constant vector

Returns

An HHL instance for a specific system of linear equations

run (backend, config)

Run the solver.

Parameters

backend - BaseBackend, the backend instance to execute the algorithm

config - Config, the configuration for the backend

Returns

None

Example

We provide an example of HHL in example/hhl_example.py

get_measurements ( )

Get the probabilities after running the solver.

Returns

A dictionary of the probabilities of different measurements from the solver

get_state ( )

Get the state vector after running the solver, working only with simulator backends.

Returns

A dictionary of the probabilities of different measurements from the solver

class spinqit.algorithm.VQE

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

__init__ (hamiltonian, optimizer, ansatz, params, depth)

Initialize a VQE solver.

Parameters

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

Returns

A VQE instance

run (mode, grad_method)

Run the solver.

Parameters

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'

Returns

A list of loss values

Example

We provide an example of VQE in example/vqe_h2_example.py

class spinqit.algorithm.QAOA

Quantum Approximate Optimization Algorithm (QAOA) is a variational algorithm to solve combinatorial optimization problems.

Methods

__init__ (problem, optimizer, depth, problem_ansatz, mixer_ansatz)

Initialize a QAOA solver.

Parameters

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

Returns

A QAOA instance

run (mode, grad_method)

Run the solver.

Parameters

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

Returns

A list of loss values

Example

We provide an example of QAOA in example/qaoa_maxcut_example.py

optimized_result

Get the measurements of the final circuit.

Returns

Execution Result after Optimization

class spinqit.algorithm.QuantumCounting

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

__init__ (counting_num, searching_num, prep, oracle, prep_params, oracle_params)

Initialize a QuantumCounting instance for a specific problem.

Parameters

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

Returns

A QuantumCounting instance

run (backend, config)

Solve the quantum counting problem.

Parameters

backend - BaseBackend, the backend instance to execute the algorithm

config - Config, the configuration for the backend

Returns

The count of targets

Example

We provide an example of quantum counting in example/quantum_counting_example.py

class spinqit.algorithm.QSearching

The QSearching algorithm searches for the index of the maximum or minimum value in an array.

Methods

__init__ (objective, backend, config, seed)

Initialize a QSearching instance.

Parameters

objective - str, 'max' or 'min'

backend - BaseBackend, the backend instance to execute the algorithm

config - Config, the configuration for the backend

seed - None, int, float, str, bytes or bytearray, the random seed used in the algorithm

Returns

A QSearching instance

search (dataset)

Search for the max or min value in the dataset.

Parameters

dataset - arraylike, the input array to search

Returns

The index of the max or min value

Example

We provide an example of quantum counting in example/search_max_min.py

class spinqit.algorithm.AmplitudeEstimation

Given an operator A that A|0> = √1-a |Ψ0> + √a |Ψ1>, this class estimates the amplitude a of the state |Ψ1>.

Methods

__init__ (eval_num, A, params, backend_mode, **kwargs)

Initialize an AmplitudeEstimation instance.

Parameters

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

Returns

An AmplitudeEstimation instance

run ()

Execute the estimation algorithm.

Returns

The estimation of the amplitude

class spinqit.algorithm.MaximumLikelihoodAmplitudeEstimation

This class implements the amplitude estimation algorithm based on maximum likelihood.

Methods

__init__ (circuit_num, A, params, alpha: float = 0.05, backend_mode, **kwargs)

Initialize a MaximumLikelihoodAmplitudeEstimation instance.

Parameters

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

Returns

An MaximumLikelihoodAmplitudeEstimation instance

run ()

Execute the estimation algorithm.

Returns

The estimation of the amplitude

class spinqit.algorithm.CoinedQuantumWalk

This class implements a coined quantum walk.

Methods

__init__ (state_qubit_num, coin_qubit_num, init_operator, coin_operator, shift_operator, backend_mode, **kwargs)

Initialize a CoinedQuantumWalk instance.

Parameters

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

Returns

A CoinedQuantumWalk instance

walk (steps)

Execute the quantum walk using the coin.

Parameters

steps - int, the number of steps to walk

Returns

The probabilities of positions after the walk

spinqit.algorithm.coined_quantum_walk.get_grover_coin (coin_qubit_num)

Generate the gate as a Grover coin for coined quantum walk.

Parameters

coin_qubit_num – int, the number of qubits used for the coin

Returns

A composite Gate as a Grover coin

class spinqit.algorithm.QSVC

QSVC is a classifier based on quantum support vector machine. Both quantum kernel and projected quantum kernel methods are available for selection.

Methods

__init__ (featuremap, use_projected, qubit_num, measure, backend_mode, **kwargs)

Create a QSVC instance with a custom quantum featuremap or basic information. Either featuremap or qubit_num must be specified.

Parameters

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

Returns

A QSVC instance

fit (X_train, y_train)

Fit the SVM model according to the given training data in the same way as the fit function of sklearn.svm.SVC.

Parameters

X_train – numpy.ndarray, the training samples

y_train – numpy.ndarray, labels for class membership of each sample

Returns

Fitted SVM estimator.

predict (X_test)

Perform classifiction on samples in X.

Parameters

X_test – numpy.ndarray, the input data

Returns

Class labels for samples in X_test

Quantum Machine Learning

SpinQit supports quantum machine learning by providing quantum encoding methods, optimizers, and objective functions. In addition, SpinQit provides interfaces to integrates with classical machine learning frameworks to conduct hybrid quantum-classical machine learning.

Interface

Integrating SpinQit QLayer as a quantum layer or module within classical frameworks is quite intuitive. This custom layer, although quantum in nature, still maintains classical inputs and outputs. However, it employs a unique method for calculating the gradients of quantum circuits. We have developed three convenient interfaces to interact with three widely-used classical machine learning frameworks: Pytorch, TensorFlow, and PaddlePaddle. These classical machine learning frameworks permit users to define functions with bespoke gradient computations. Accordingly, SpinQit establishes forward and backward functions for quantum computing that can cooperate with classical training. SpinQit also introduces simple quantum layers directly applicable in these traditional frameworks. It should be noted, however, that a layer in a machine learning model might encompass more than just a quantum circuit. As such, these simple layers may not satisfy all users’ needs. In such cases, users are enabled to create their own quantum layers/modules. We provide two examples at the end of this document to show how these interfaces work with classical frameworks.

Pytorch

class spinqit.interface.torch_interface.QuantumFunction

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

forward (ctx, kwargs, *params)
Parameters

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

backward (ctx, grad_output)
Parameters

ctx - torch.autograd.function.FunctionCtx, context between forward and backward

grad_output – torch.Tensor, the gradient w.r.t the forward output

class spinqit.interface.torch_interface.QuantumModule

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 unique quantum module built upon QuantumFunction.

Methods

__init__ (quantum_layer, weight_shape, bias)

Create a QuantumModule that can be used in a Pytorch network for hybrid classical-quantum machine learning.

Parameters

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

Returns

A QuantumModule instance

forward (state)
Parameters

state - torch.Tensor, the training or test data

TensorFlow 2.0

spinqit.interface.tf_interface.get_quantum_func (qlayer)

This function uses tensorflow.custom_gradient to define a function to return the forward result and gradient function in the context of quantum computing.

Parameters

qlayer – QLayer, the interface wrapping circuit and execution configuration

Returns

A function returning the forward result and gradient function

class spinqit.interface.tf_interface.QuantumLayer

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

__init__ (quantum_layer, weight_shape, bias)

Create a QuantumLayer that can be used in a TensorFlow network for hybrid classical-quantum machine learning.

Parameters

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

Returns

A QuantumLayer instance

call (state)
Parameters

state - tensorflow.Variable, the training or test data

PaddlePaddle

class spinqit.interface.paddle_interface.QuantumFunction

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

forward (ctx, kwargs, *params)
Parameters

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

backward (ctx, dy)
Parameters

ctx - paddle.autograd. PyLayerContext, context between forward and backward

dy – paddle.Tensor, the gradient w.r.t the forward output

Encoding

Currently, there are three off-the-shelf encoding functions which convert classical information into quantum states or operations. These encoding functions can be used for quantum feature maps. Users can also define their own encoding circuit.

spinqit.primitive.amplitude_encoding (vector, qubits)

Encodes classical information into amplitudes of quantum states. The amplitude of each quantum state is associated with a specific classical value in the input vector. The normalized state vector is equal to the normalized input vector.

Parameters

vector – numpy.ndarray, the input classical vector

qubits - List, the qubits to encode the input vector

Returns

The instructions prepare quantum states to encode the given vector.

spinqit.primitive.angle_encoding (vector, qubits, depth, rotate_gate)

Encodes classical information into parameters of rotation gates.

Parameters

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

Returns

The instructions for the rotation gates.

spinqit.primitive.iqp_encoding (vector, qubits, depth, ring_pattern)

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.

Parameters

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

Returns

The instructions for the instantaneous quantum polynomial circuit

spinqit.primitive.basis_encoding (vector, qubits)

Encodes classical binary information into a quantum circuit. Apply the X gate to the ith qubit when the ith element is 1.

Parameters

vector – numpy.ndarray, the input classical binary vector

qubits - List, the qubits to encode the input vector

Returns

The instructions prepare quantum states to encode the given vector.

Objective Function

SpinQit supports not only classical objective functions based on measurements, but also quantum objective functions. These include Fidelity, VNEntropy, MutualInfo, and RelativeEntropy.

class spinqit.algorithm.loss.Fidelity

An objective function calculating the state fidelity.

Methods

__call__ (state, target_state)

Calculate the fidelity between a state and a target state.

Parameters

state – list or torch.Tensor like, the input state vector

target_state – list or torch.Tensor like, the target state vector

Returns

The fidelity value

class spinqit.algorithm.loss.VNEntropy

An objective function calculating the Von Neumann Entropy.

Methods

__init__ (log_base)

Create a VNEntropy instance.

Parameters

log_base – float, log(log_base) is used as the dividend in the computation of the entropy

Returns

A VNEntropy instance

__call__ (state, indices)

Calculate the Von Neumann entropy of a state.

Parameters

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

Returns

The Von Neumann entropy

class spinqit.algorithm.loss.MutualInfo

An objective function calculating the mutual information.

Methods

__init__ (log_base)

Create a MutualInfo instance.

Parameters

log_base – float, log(log_base) is used as the dividend in the computation of the VN entropies

Returns

A MutualInfo instance

__call__ (state, indices)

Calculate the mutual information between two subsystems.

Parameters

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

Returns

The mutual information between two subsystems

class spinqit.algorithm.loss.RelativeEntropy

An objective function calculating the relative entropy.

Methods

__init__ (log_base)

Create a RelativeEntropy instance.

Parameters

log_base – float, log(log_base) is used as the dividend in the computation of the VN entropies

Returns

A RelativeEntropy instance

__call__ (state0, state1)

Calculate the relative entropy between two states.

Parameters

state0 – list or torch.Tensor like, the first input state vector

state1 – list or torch.Tensor like, the second input state vector

Returns

The relative entropy

Optimizer

SpinQit has three native optimizers and three interfaces to use optimizers from SciPy, PyTorch and Noisyopt.

class spinqit.algorithm.optimizer.ADAM

Native implementation of ADAM optimizer in SpinQit.

Methods

__init__ (maxiter, tolerance, learning_rate, beta1, beta2, noise_factor, verbose)

Create an ADAM optimizer instance.

Parameters

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

Returns

An ADAM instance

optimize (qlayer, *params)

Optimize the objective function.

Parameters

qlayer – QLayer, the interface wrapping circuit and execution configuration

*params - Parameter, parameters used in the quantum circuit

Returns

The list of loss values

class spinqit.algorithm.optimizer.GradientDescent

Native implementation of gradient descent optimizer in SpinQit.

Methods

__init__ (maxiter, tolerance, learning_rate, verbose)

Create a GradientDescent optimizer instance.

Parameters

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

Returns

A GradientDescent instance

optimize (qlayer, *params)

Optimize the objective function.

Parameters

qlayer – QLayer, the interface wrapping circuit and execution configuration

*params - Parameter, parameters used in the quantum circuit

Returns

The list of loss values

class spinqit.algorithm.optimizer.QuantumNaturalGradient

Implementation of quantum natural gradient optimizer in SpinQit

Methods

__init__ (maxiter, tolerance, learning_rate, verbose)

Create a QuantumNaturalGradient optimizer instance.

Parameters

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

Returns

A QuantumNaturalGradient instance

optimize (qlayer, *params)

Optimize the objective function.

Parameters

qlayer – Qlayer, the interface wrapping circuit and execution configuration

*params - Parameter, parameters used in the quantum circuit

Returns

The list of loss values

class spinqit.algorithm.optimizer.TorchOptimizer

Interface to use optimizers in PyTorch, including NAdam, Adam, SGD, AdamW, Adagrad

Methods

__init__ (maxiter, tolerance, learning_rate, verbose, optim_type, **kwargs)

Create a TorchOptimizer instance to call optimizers in PyTorch.

Parameters

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

Returns

An interface instance that calls the optimizers in PyTorch

optimize (qlayer, *params)

Optimize the objective function.

Parameters

qlayer – Qlayer, the interface wrapping circuit and execution configuration

*params - Parameter, parameters used in the quantum circuit

Returns

The list of loss values

class spinqit.algorithm.optimizer.ScipyOptimizer

Interface to call optimizers in SciPy, specifically, "Nelder-Mead" and "COBYLA"

Methods

__init__ (maxiter, tolerance, verbose, method, **kwargs)

Create a ScipyOptimizer instance to call optimizers in SciPy.

Parameters

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'

Returns

An interface instance that calls the optimizers in SciPy

optimize (fn, *params)

Optimize the objective function.

Parameters

fn – Qlayer, the interface wrapping circuit and execution configuration

*params - Parameter, parameters used in the quantum circuit

Returns

The list of loss values

class spinqit.algorithm.optimizer.SPSAOptimizer

Interface to use the minimizeSPSA optimizer from noisyopt.

Methods

__init__ (maxiter, verbose, a, c, **kwargs)

Create a SPSAOptimizer instance to call the minimizeSPSA optimizer.

Parameters

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

Returns

An interface instance that calls the minimizeSPSA optimizer

optimize (qlayer, *params)

Optimize the objective function.

Parameters

qlayer – Qlayer, the interface wrapping circuit and execution configuration

*params - Parameter, parameters used in the quantum circuit

Returns

The list of loss values

Solver

SpinQit provides two off-the-shelf problem solvers based on quantum algorithms. The satisfaction problem (SAT) and the traveling salesman problem (TSP) can model many real-world application problems and can by solved by quantum algorithms efficiently.

SATSolver

class spinqit.solver.SATSolver

A solver to solve the satisfaction problem using Grover's algorithm.

Methods

__init__ (expr)

Create a SATSolver instance for a specific satisfaction problem.

Parameters

expr – str or sympy.logic.boolalg.And, the expression that represents the satisfaction problem to solve

Returns

An instance of SATSolver

solve (backend_mode, **kwargs)

Solve the satisfaction on the given backend.

Parameters

backend_mode - str, the backend to execute the quantum circuit, one of 'spinq', 'torch', 'qasm', 'nmr', and 'cloud'

**kwargs - Any, configurations for the backend

Returns

The assignment satisfying the constraints

TSPSolver

class spinqit.solver.TSPSolver

A solver to solve the traveling salesman problem using VQE algorithm.

Methods

__init__ (vertex_num, weighted_adjacency, penalty)

Create a TSPSolver instance for a specific graph.

Parameters

vertex_num – int, the number of vertices

weighted_adjacency – list or numpy.ndarray, the weighted adjacency matirx in which weighted_adjacency[i][j] is the weight for the edge i to j

penalty – float, a parameter required in the algorithm whose value must be larger than the maximum weight

Returns

An instance of TSPSolver

solve (iterations, backend_mode, grad_method, learning_rate)

Solve the TSP problem with specific configurations.

Parameters

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

Returns

The visiting order of vertices