<jupyter_start><jupyter_text>Solving Linear Equations<jupyter_code># reference - # https://quantumcomputing.stackexchange.com/questions/20862/hhl-the-result-is-correct-for-one-matrix-but-wrong-for-another-one<jupyter_output><empty_output><jupyter_text>https://www.youtube.com/watch?v=KtIPAPyaPOg<jupyter_code>from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, Aer, execute, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Statevector

from qiskit.algorithms.linear_solvers.hhl import HHL

import numpy as np
import math as m

# decimal to binary
def dec2bin(decimal, bits):
    b = bin(decimal)
    b = b[2:len(b)]
    while len(b) < bits:
        b = '0' + b
    return b

processor = Aer.backends(name='qasm_simulator')[0]
processor<jupyter_output><empty_output><jupyter_text>![image.png](attachment:fa6faba6-ce99-4992-81bf-e329e6bd65aa.png)<jupyter_code># 1st linear system; A*x = B
matrix_A = np.array([[1,0,0,0],[0,2,0,0],[0,0,3,0],[0,0,0,4]])
vector_b = np.array([1,4,0.5,3]) 

# solution = [1, 2, 0.1667, 0.75]

matrix_A
# number of variables (assuming n=2^k)
n = len(matrix_A[2,:])
n
# number of necessary qubits
n_qubits = m.ceil(m.log(n,2))
n_qubits
# norm of right-side
bNorm = np.linalg.norm(vector_b)
bNorm
hhlSolver = HHL(quantum_instance = processor)
hhlSolver
# preparing circuit in general form
hhlCircuit = hhlSolver.construct_circuit(matrix_A, vector_b)
hhlCircuit.draw()
# transpile -- adapt circuit to real quantum processor
circuitToRun = transpile(hhlCircuit, basis_gates=['id', 'rz', 'sx', 'x', 'cx'])

# add measurement
circuitToRun.measure_all()

circuitToRun.draw()
from qiskit.visualization import plot_histogram

# execute the circuit
shots = 8192
counts = execute(circuitToRun, processor, shots=shots).result().get_counts(circuitToRun)
plot_histogram(counts)
# width - num of qubits and classical bit summed
usedQubits = circuitToRun.width()/2
usedQubits
# working qubits
zeros = dec2bin(0, usedQubits - n_qubits - 1)

# ancilla qubit has to be |1>, working qubits |0>, results are in last "n_qubits" qubits
# e.g. if n_qubits and total qubits is 6, then 3 are working qubits
# results are stored in |1 000 00>, |1 000 01>, |1 000 10>, |1 000 11>
for i in range(0,n):
    indx = '1' + zeros + dec2bin(i, n_qubits)
    # bNorm*m.sqrt(M[indx]/shots) - we need probability amplitudes => sqrt
    # and adjust them by norm of vector b to get "unnormalized" solution x
    print('x_' + str(i) + ': ' + str(round(bNorm*m.sqrt(counts[indx]/shots),4)))<jupyter_output>x_0: 0.9886
x_1: 2.0125
x_2: 0.1498
x_3: 0.7271
{'fraction_non_alphanumeric': 0.13377023901310717, 'fraction_numerical': 0.047802621434078645, 'mean_word_length': 5.298543689320389, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 19, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '503458', 'license': 'MIT', 'n_tokens_mistral': 1094, 'n_tokens_neox': 990, 'n_words': 236, 'path': 'Notebooks/Algorithms/.ipynb_checkpoints/QuantumLinearSolver_HHL_1.2-checkpoint.ipynb', 'repo_name': 'praveentn/ml-repos', 'size': '2594'}