Skip to content

Latest commit

 

History

History
298 lines (167 loc) · 9.05 KB

File metadata and controls

298 lines (167 loc) · 9.05 KB

module vqls_prototype.vqls

Variational Quantum Linear Solver

See https://arxiv.org/abs/1909.05820


class VQLSLog

VQLSLog(values: List, parameters: List)


method update

update(count, cost, parameters)

class VQLS

Systems of linear equations arise naturally in many real-life applications in a wide range of areas, such as in the solution of Partial Differential Equations, the calibration of financial models, fluid simulation or numerical field calculation. The problem can be defined as, given a matrix :math:A\in\mathbb{C}^{N\times N} and a vector :math:\vec{b}\in\mathbb{C}^{N}, find :math:\vec{x}\in\mathbb{C}^{N} satisfying :math:A\vec{x}=\vec{b}.

 from qalcore.qiskit.vqls.vqls import VQLS, VQLSLog  
 from qiskit.circuit.library.n_local.real_amplitudes import RealAmplitudes  
 from qiskit_algorithms import optimizers as opt  
 from qiskit_aer import Aer, BasicAer  
 import numpy as np 

 from qiskit.quantum_info import Statevector  
 import matplotlib.pyplot as plt  f
 rom qiskit.primitives import Estimator, Sampler, BackendEstimator 

 # create random symmetric matrix  
 A = np.random.rand(4, 4)  A = A + A.T 

 # create rhight hand side  
 b = np.random.rand(4) 

 # solve using numpy  
 classical_solution = np.linalg.solve(A, b / np.linalg.norm(b))  
 ref_solution = classical_solution / np.linalg.norm(classical_solution) 

 # define the wave function ansatz  
 ansatz = RealAmplitudes(2, entanglement="full", reps=3, insert_barriers=False) 

 # define an estimator primitive  
 estimator = Estimator() 

 # define the logger  
 log = VQLSLog([],[]) 

 # create the solver  
 vqls = VQLS(  estimator,  ansatz,  opt.CG(maxiter=200),  callback=log.update  ) 

 # solve   
 res = vqls.solve(A, b, opt)  vqls_solution = np.real(Statevector(res.state).data) 

 # plot solution  
 plt.scatter(ref_solution, vqls_solution)  plt.plot([-1, 1], [-1, 1], "--")  plt.show() 

 # plot cost function   
 plt.plot(log.values)  plt.ylabel('Cost Function')  plt.xlabel('Iterations')  plt.show() 

References:

[1] Carlos Bravo-Prieto, Ryan LaRose, M. Cerezo, Yigit Subasi, Lukasz Cincio, Patrick J. Coles Variational Quantum Linear Solver arXiv:1909.05820 <https://arxiv.org/abs/1909.05820>

method __init__

__init__(
    estimator: BaseEstimator,
    ansatz: QuantumCircuit,
    optimizer: Union[Optimizer, Minimizer],
    sampler: Optional[BaseSampler] = None,
    initial_point: Optional[ndarray] = None,
    gradient: Optional[GradientBase, Callable] = None,
    max_evals_grouped: Optional[int] = 1,
    callback: Optional[Callable[[int, ndarray, float, float]], NoneType] = None
) → None

Args:

  • estimator: an Estimator primitive to compute the expected values of the quantum circuits needed for the cost function
  • ansatz: A parameterized circuit used as Ansatz for the wave function.
  • optimizer: A classical optimizer. Can either be a Qiskit optimizer or a callable that takes an array as input and returns a Qiskit or SciPy optimization result.
  • sampler: a Sampler primitive to sample the output of some quantum circuits needed to compute the cost function. This is only needed if overal Hadammard tests are used.
  • initial_point: An optional initial point (i.e. initial parameter values) for the optimizer. If None then VQLS will look to the ansatz for a preferred point and if not will simply compute a random one.
  • gradient: An optional gradient function or operator for optimizer.
  • max_evals_grouped: Max number of evaluations performed simultaneously. Signals the given optimizer that more than one set of parameters can be supplied so that potentially the expectation values can be computed in parallel. Typically this is possible when a finite difference gradient is used by the optimizer such that multiple points to compute the gradient can be passed and if computed in parallel improve overall execution time. Deprecated if a gradient operator or function is given.
  • callback: a callback that can access the intermediate data during the optimization. Three parameter values are passed to the callback as follows during each evaluation by the optimizer for its current set of parameters as it works towards the minimum.
  • These are: the evaluation count, the cost and the optimizer parameters for the ansatz

property ansatz

Returns the ansatz.


property callback

Returns callback


property initial_point

Returns initial point


property max_evals_grouped

Returns max_evals_grouped


property num_clbits

return the numner of classical bits


property num_qubits

return the numner of qubits


property optimizer

Returns optimizer


method construct_circuit

construct_circuit(
    matrix: Union[ndarray, QuantumCircuit, List],
    vector: Union[ndarray, QuantumCircuit],
    options: Dict
) → List[QuantumCircuit]

Returns the a list of circuits required to compute the expectation value

Args:

  • matrix (Union[np.ndarray, QuantumCircuit, List]): matrix of the linear system
  • vector (Union[np.ndarray, QuantumCircuit]): rhs of thge linear system
  • options (Dict): Options to compute define the quantum circuits that compute the cost function

Raises:

  • ValueError: if vector and matrix have different size
  • ValueError: if vector and matrix have different numner of qubits
  • ValueError: the input matrix is not a numoy array nor a quantum circuit

Returns:

  • List[QuantumCircuit]: Quantum Circuits required to compute the cost function

method get_coefficient_matrix

get_coefficient_matrix(coeffs) → ndarray

Compute all the vi* vj terms

Args:

  • coeffs (np.ndarray): list of complex coefficients

method get_cost_evaluation_function

get_cost_evaluation_function(
    hdmr_tests_norm: List,
    hdmr_tests_overlap: List,
    coefficient_matrix: ndarray,
    options: Dict
) → Callable[[ndarray], Union[float, List[float]]]

Generate the cost function of the minimazation process

Args:

  • hdmr_tests_norm (List): list of quantum circuits needed to compute the norm
  • hdmr_tests_overlap (List): list of quantum circuits needed to compute the norm
  • coefficient_matrix (np.ndarray): the matrix values of the c_n^* c_m coefficients
  • options (Dict): Option to compute the cost function

Raises:

  • RuntimeError: If the ansatz is not parametrizable

Returns:

  • Callable[[np.ndarray], Union[float, List[float]]]: the cost function

method solve

solve(
    matrix: Union[ndarray, QuantumCircuit, List[QuantumCircuit]],
    vector: Union[ndarray, QuantumCircuit],
    options: Optional[Dict] = None
) → VariationalLinearSolverResult

Solve the linear system

Args:

  • matrix (Union[List, np.ndarray, QuantumCircuit]): matrix of the linear system
  • vector (Union[np.ndarray, QuantumCircuit]): rhs of the linear system
  • options (Union[Dict, None]): options for the calculation of the cost function

Returns:

  • VariationalLinearSolverResult: Result of the optimization and solution vector of the linear system

This file was automatically generated via lazydocs.