from qiskit_ibm_runtime import QiskitRuntimeService

QiskitRuntimeService.save_account(channel='ibm_quantum', 
                                  token='83ab2a86232e48767228534cdae2cf55b8e8ea4e0eb1e57804268f40d7bee64692f719528e8871de617ffc35040d21bd389f4696313f46900c077c7f617a1512',
                                  overwrite=True)

service = QiskitRuntimeService(instance='ibm-q/open/main')

print(service.backends())

from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw()

from qiskit_ibm_runtime import Sampler, Options, Session

options = Options(optimization_level=1)

with Session(service=service, backend="ibmq_qasm_simulator") as session:
    sampler = Sampler(session=session, options=options)
    job = sampler.run(circuits=qc) # foi usado 18 s dos 10 min (por conjunto de 4000 prepara-evolui-mede experimentos)

job.result() # 'probabilidades' (eles chamam de quasiprobabilidades)

counts = job.result().quasi_dists[0].binary_probabilities()
counts

from qiskit.visualization import plot_histogram
plot_histogram(counts)

backend = service.get_backend("ibm_osaka")

with Session(service=service, backend=backend) as session:
    sampler = Sampler(session=session, options=options)
    job = sampler.run(circuits=qc)
    print(job.job_id())

jobr = service.job('cnvn5zzvn4c0008a6df0')
jobr.result()

counts = jobr.result().quasi_dists[0].binary_probabilities()
counts  # ?

plot_histogram(counts) 

print(jobr.logs())

from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
 
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator
 
service = QiskitRuntimeService(channel="ibm_cloud")
 
psi1 = RealAmplitudes(num_qubits=2, reps=2)
 
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])
 
with Session(service=service, backend="ibmq_qasm_simulator") as session:
    estimator = Estimator(session=session)
 
    theta1 = [0, 1, 1, 2, 3, 5]
 
    # calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
    psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1])
    print(psi1_H1.result())
 
    # calculate [ <psi1(theta1)|H2|psi1(theta1)>, <psi1(theta1)|H3|psi1(theta1)> ]
    psi1_H23 = estimator.run(
        circuits=[psi1, psi1],
        observables=[H2, H3],
        parameter_values=[theta1]*2
    )
    print(psi1_H23.result())

