import pylab
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT

satProblem = '3sat2-3.cnf'
with open(satProblem, 'r') as f:
    sat_cnf = f.read()
print(sat_cnf)

sat_oracle = SAT(sat_cnf)

algorithm = Grover(sat_oracle)

backend = Aer.get_backend('qasm_simulator')
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])

plot_histogram(result['measurements'])

params = {
    'problem': {'name': 'search'},
    'algorithm': {
        'name': 'Grover'
    },
    'oracle': {
        'name': 'SAT',
        'cnf': sat_cnf
    },
    'backend': {
        'shots': 100
    }
}

result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurements'])

# Authenticate for access to remote backends
try:
    import Qconfig
    IBMQ.load_accounts()
except:
    print("""WARNING: There's no connection with the API for remote backends.
             Have you initialized a file with your personal token?
             For now, there's only access to local simulator backends...""")

backend = least_busy(IBMQ.backends(simulator=False))
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])

