from qiskit_alice_bob_provider import AliceBobLocalProvider
from qiskit_aer import AerSimulator
import tempfile
from qiskit import transpile, execute, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit_algorithms import AmplificationProblem
from qiskit_algorithms import Grover
from qiskit.primitives import BackendSampler
from qiskit.tools.visualization import plot_histogram
import numpy as np
from tqdm.notebook import tqdm
from matplotlib import pyplot as plt

provider = AliceBobLocalProvider()
provider.backends()

backend = provider.get_backend('EMU:40Q:LOGICAL_TARGET')

input_3sat_instance = """
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
"""
with tempfile.NamedTemporaryFile(mode='w+t', delete=True) as fp:
    fp.write(input_3sat_instance)
    fp.flush()
    oracle = PhaseOracle.from_dimacs_file(fp.name)

oracle.draw('mpl')

transpile(oracle, backend).draw('mpl')

problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
sampler = BackendSampler(backend, options={'shots': 100_000})
grover = Grover(sampler=sampler)
result = grover.amplify(problem)

sampler.circuits[0].draw('mpl')

sampler.circuits[0].decompose().decompose().draw('mpl')

sampler.transpiled_circuits[0].draw('mpl')

plot_histogram(result.circuit_results[0])

degraded_backend = provider.get_backend('EMU:15Q:LOGICAL_EARLY', average_nb_photons=4, distance=5)

problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
sampler = BackendSampler(degraded_backend, options={'shots': 100_000})
grover = Grover(sampler=sampler)
result = grover.amplify(problem)

plot_histogram(result.circuit_results[0])