Use this file to discover all available pages before exploring further.
View on GitHub
Open this notebook in GitHub to run it yourself
Guidance for the workshop:
The # TODO is there for you to do yourself.
**The # Solution start and # Solution end are only for helping you.Try doing it yourself…**Solving linear equations appears in many research, engineering, and design fields.For example, many physical and financial models, from fluid dynamics to portfolio optimization, are described by partial differential equations, which are typically treated by numerical schemes, most of which are eventually transformed to a set of linear equations.The HHL algorithm [1] is a quantum algorithm for solving a set of linear equations. It is one of the fundamental quantum algorithms that is expected to give a speedup over its classical counterpart.A set of linear equations of size N is represented by an N×N matrix and a vector b of size N, Ax=b, where the solution to the problem is designated by the solution variable x.For simplicity, the demo below treats a usecase where b is a normalized vector ∣b∣=1, and A is an Hermitian matrix of size 2n×2n, whose eigenvalues are in the interval (0,1).Generalizations to other usecases are discussed at the end of this demo.
import numpy as npimport scipy as scipyA = np.array( [ [0.28, -0.01, 0.02, -0.1], [-0.01, 0.5, -0.22, -0.07], [0.02, -0.22, 0.43, -0.05], [-0.1, -0.07, -0.05, 0.42], ])b = np.array([1, 2, 4, 3])b = b / np.linalg.norm(b)print("A =", A, "\n")print("b =", b, "\n")# verifying that the matrix is symmetric and has eigenvalues in [0,1)if not np.allclose(A, A.T, rtol=1e-6, atol=1e-6): raise Exception("The matrix is not symmetric")w, v = np.linalg.eig(A)for lam in w: if lam < 0 or lam > 1: raise Exception("Eigenvalues are not in (0,1)")sol_classical = np.linalg.solve(A, b)print("Classical solution: x = ", sol_classical)num_qubits = int(np.log2(len(b)))
The first stage of the HHL algorithm is to load the normalized RHS vector b into a quantum register:∣0⟩nSPi=0∑2n−1bi∣i⟩nwhere ∣i⟩ are states in the computational basis.Comments:
The relevant built-in function is the prepare_amplitudes one, which gets 2n values of b, as well as an upper bound for its functional error through the bound parameter.
from classiq import *@qfuncdef load_b(b: CArray[CReal], res: Output[QArray]) -> None: # TODO prepare the state |b> in the "res" register - the amplitude of res states correspond to the values of the vector b # Solution start prepare_amplitudes(b, 0.0, res) # Solution end
@qfuncdef main(res: Output[QArray]): load_b(b.tolist(), res)qmod_b_load = create_model(main)# TODO update the qmod to have aer_simulator_statevector as backend, with one shot# Solution startqmod_b_load = set_execution_preferences( qmod_b_load, num_shots=1, backend_preferences=ClassiqBackendPreferences(backend_name="simulator_statevector"),)# Solution endqprog_b_load = synthesize(qmod_b_load)show(qprog_b_load)
Output:
Quantum program link: https://platform.classiq.io/circuit/2yjDzAXzUnVNMS5hsJGubDIKBR7
Take a look at the resulted circuit.Now let’s execute and see if b was built correctly
job = execute(qprog_b_load)job.open_in_ide()
Check if you see a match between the original b to the resulted state vector
print("The original b is: ", b)result = job.result_value()print("The resulted state vector :", result.state_vector)
Output:
The original b is: [0.18257419 0.36514837 0.73029674 0.54772256] The resulted state vector : {'00': (0.18257418583505527+0j), '01': (0.3651483716701124+0j), '10': (0.7302967433402199+0j), '11': (0.5477225575051674+0j)}
2.1.2 Quantum Phase Estimation (QPE) for the Hamiltonian Evolution U=e2πiA
The QPE function block, which is at the heart of the HHL algorithm, operates as follows: Unitary matrices have eigenvalues of norm 1, and thus are of the form e2πiλ, with 0≤λ<1.For a quantum state ∣ψ⟩n, prepared in an eigenvalue of some unitary matrix U of size 2n×2n, the QPE algorithm encodes the corresponding eigenvalue into a quantum register:∣0⟩m∣ψ⟩nQPE(U)∣λ⟩m∣ψ⟩n,where m is the precision of the binary representation of λ, λ=2m1∑k=02m−1λ(k)2k with λ(k) being the state of the k-th qubit.In the HHL algorithm a QPE for the unitary U=e2πiA is applied.The mathematics: First, note that the eigenvectors of U are the ones of the matrix A, and that the corresponding eigenvalues λ defined for U=e2πiA are the eigenvalues of A. Second, represent the prepared state in the basis given by the eigenvalues of A.This is merely a mathematical transformation; with no algorithmic considerations here. If the eigenbasis of A is given by the set {∣ψj⟩n}j=02n−1, theni=0∑2n−1bi∣i⟩n=j=0∑2n−1βj∣ψj⟩n.Applying the QPE stage gives∣0⟩mj=0∑2n−1βj∣ψj⟩nQPEj=0∑2n−1βj∣λj⟩m∣ψj⟩n.Comments:
The next step in the HHL algorithm is to pass the inverse of the eigenvalue registers into their amplitudes, using the Amplitude Loading (AL) construct.Given a function f:[0,1)→[−1,1], it implements ∣0⟩∣λ⟩mAL(f)f(λ)∣1⟩∣λ⟩m+1−f2(λ)∣0⟩∣λ⟩m.For the HHL algorithm, apply an AL with f=C/x where C is a lower bound for the minimal eigenvalue of A.Applying this AL givesj=0∑2n−1βj∣λj⟩m∣ψj⟩nAL(C/x)∣0⟩(j=0∑2n−11−λj2C2βj∣λj⟩m∣ψj⟩n)+∣1⟩(j=0∑2n−1λjCβj∣λj⟩m∣ψj⟩n),where C is a normalization coefficient.The normalization coefficient C, which guarantees that the amplitudes are normalized, can be taken as the lower possible eigenvalue that can be resolved with the QPE:C=1/2precision.The built-in construct to define an amplitude loading is the assign_amplitude_table function.
@qfuncdef simple_eig_inv(phase: Const[QNum], indicator: Output[QBit]): # TODO allocate 1 qubit for indicator # TODO load its |1> state amplitude to be C/phase using the assign_amplitude_table function # Solution start allocate(indicator) assign_amplitude_table( lookup_table(lambda p: 0 if p == 0 else (1 / 2**phase.size) / p, phase), phase, indicator, ) # Solution end
As the final step in the HHL model, clean the QPE register by applying an inverse-QPE. (Note that it is not guaranteed that this register is completely cleaned; namely, that all the qubits in the QPE register return to zero after the inverse-QPE.Generically they are all zero with very high probability).In this model we will simply call the QPE function with the same parameters in stage
This is how the quantum state looks now
∣0⟩(j=0∑2n−11−λj2C2βj∣λj⟩m∣ψj⟩n)+∣1⟩(j=0∑2n−1λjCβj∣λj⟩m∣ψj⟩n)inv−QPE(U)∣0⟩m∣0⟩(j=0∑2n−11−λj2C2βj∣ψj⟩n)+∣0⟩m∣1⟩(j=0∑2n−1λjCβj∣ψj⟩n)The state entangled with ∣1⟩ stores the solution to our problem (up to some normalization problem)j=0∑2n−1λjCβjψj=Cx.
Let’s remind that the entire HHL algorithm is composed of:
State preparation of the RHS vector b.
QPE for the unitary matrix e2πiA, which encodes eigenvalues on a quantum register of size m.
An inversion algorithm that loads amplitudes according to the inverse of the eigenvalue registers.
An inverse QPE with the parameters in (2).
And put all together in my_hhl functionYou can apply QPE\dagger * EigenValInv * QPE using the within_apply operator
@qfuncdef my_hhl( fraction_digits: int, b: CArray[CReal], unitary_with_matrix: QCallable[QArray], res: Output[QArray], phase: Output[QNum], indicator: Output[QBit],) -> None: # TODO Call load_b you created, to load "b" vector into register "res" # Solution start load_b(b, res) # Solution end # TODO allocate a qnum register for "phase".This qnum should be in the range [0,1) with fraction_digits precision # Solution start allocate(fraction_digits, False, fraction_digits, phase) # Solution end # TODO refer to applying (QPE\dagger)*(EigenValInv)*(QPE) : we want to apply "simple_eig_inv" within "qpe" # Solution start within_apply( lambda: qpe(unitary=lambda: unitary_with_matrix(res), phase=phase), lambda: simple_eig_inv(phase=phase, indicator=indicator), ) # Solution end
The first entry point of any model would be the main function.Since you already have done all the job in my_hhl function, all we have to do now is to call it with the relevant inputsCall my_hhl with QPE_SIZE digits resolution, on the normalized b, where the unitary is based on unitary_mat.
QPE_SIZE = 4@qfuncdef main(res: Output[QNum], phase: Output[QNum], indicator: Output[QBit]): b_normalized = b.tolist() unitary_mat = scipy.linalg.expm(1j * 2 * np.pi * A).tolist() # TODO call my_hhl with QPE_SIZE digits resolution, on the normalized b, where the unitary is based on "unitary_mat" # Solution start my_hhl( fraction_digits=QPE_SIZE, b=b_normalized, unitary_with_matrix=lambda target: unitary(elements=unitary_mat, target=target), res=res, phase=phase, indicator=indicator, ) # Solution end
Here we execute the circuit on state vector simulator (the backend for execution is defined before the synthesis stage).
We can show the results in the IDE and save the state-vector into a variable.
We would like to look at the answers that are encoded in the amplitudes of the terms that their indicator qubit value=1
target_pos = result.physical_qubits_map["indicator"][0] # position of control qubitsol_pos = list(result.physical_qubits_map["res"]) # position of solutionphase_pos = list( result.physical_qubits_map["phase"]) # position of the “phase” register, and flips for endianness as we will use the indices to read directly from the string
Define a run over all the relevant strings holding the solution.The solution vector will be inserted into the variable qsol.Factor out C=1/2m.
qsol = [ np.round(parsed_state.amplitude / (1 / 2**QPE_SIZE), 5) for solution in range(2**num_qubits) for parsed_state in result.parsed_state_vector if parsed_state["indicator"] == 1.0 and parsed_state["res"] == solution and parsed_state["phase"] == 0.0 # this takes the entries where the “phase” register is at state zero]print("Quantum Solution: ", np.abs(qsol) / np.linalg.norm(qsol))print("Classical Solution: ", sol_classical / np.linalg.norm(sol_classical))
Note that the HHL algorithm returns a statevector result up to some global phase (coming from transpilation or from the quantum functions themselves). Therefore, to compare with the classical solution, correct for this global phase.
The usecase treated above is a canonical one, assuming the following properties:
The RHS vector b is normalized.
The matrix A is an Hermitian one.
The matrix A is of size 2n×2n.
The eigenvalues of A are in the range (0,1).
However, any general problem that does not follow these conditions can be resolved as follows:
As preprocessing, normalize b and then return the normalization factor as a post-processing
Symmetrize the problem as follows:
(0AAT0)(b0)=(0x).This increases the number of qubits by
Complete the matrix dimension to the closest 2n with an identity matrix.
The vector b will be completed with zeros.(A00I)(b0)=(x0).
If the eigenvalues of A are in the range [−wmin,wmax] you can employ transformations to the exponentiated matrix that enters into the Hamiltonian simulation, and then undo them for extracting the results:
A~=(A+wminI)(1−2m1)wmin+wmax1.The eigenvalues of this matrix lie in the interval [0,1), and are related to the eigenvalues of the original matrix viaλ=(wmin+wmax)λ~[1/(1−2nm1)]−wmin,with λ~ being an eigenvalue of A~ resulting from the QPE algorithm.This relation between eigenvalues is then used for the expression inserted into the eigenvalue inversion, via the AmplitudeLoading function.