import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram

F = np.matrix([[1, 1, 1], [0, 0, 1], [1, 0, 0], [0.5, 1, 0]])


print("rank", np.linalg.matrix_rank(F))

y = np.array([0, 0, 1, 0])
y.resize((4, 1))
print("F=", F)
print("y=", y)

A = F.getH() * F

A = np.pad(A, ((0, 1), (0, 1)))
A[-1][-1] = 1 

b = F.getH() * y
b = np.vstack((b, [0]))

from qiskit.algorithms.linear_solvers.hhl import HHL

backend = Aer.get_backend('aer_simulator')
hhl = HHL(quantum_instance=backend)
accurate_solution = hhl.solve(A, b)


nShots = 10000

c = ClassicalRegister(2, 'c')
qc = QuantumCircuit(c)

lambda_circ = accurate_solution.state
lambda_circ = lambda_circ.compose(qc)
lambda_circ.measure(range(2), c)


backend_qasm = Aer.get_backend('qasm_simulator')
res = execute(lambda_circ, backend_qasm, shots=nShots).result() 

counts = res.get_counts()
plot_histogram(counts)    
