Using Real Quantum Computers

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit_ibm_runtime import SamplerV2 as Sampler
/Users/butlerju/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
  warnings.warn(
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
print(circuit)
     ┌───┐     ┌─┐   
q_0: ┤ H ├──■──┤M├───
     └───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
          └───┘ ║ └╥┘
c: 2/═══════════╩══╩═
                0  1 
simulator = AerSimulator()
results = simulator.run(circuit).result().get_counts()
plot_histogram(results)

# Construct a simulator using a noise model from a real backend.
provider = QiskitRuntimeService(channel="ibm_quantum", token="fbc77e68310da5c90990728b892ef5e327787a28a126ad837f8fb88280922284da2784a01e90dc9ccd3be7d48bbe76ca0b8375ac0d3f0f312b1e19da181a18ed")
backend = provider.get_backend("ibm_kyiv")
aersim_backend = AerSimulator.from_backend(backend)
# Perform noisy simulation
results = aersim_backend.run(circuit).result().get_counts()
plot_histogram(results)

from qiskit_ibm_runtime import QiskitRuntimeService
 
service = QiskitRuntimeService(channel="ibm_quantum",token="fbc77e68310da5c90990728b892ef5e327787a28a126ad837f8fb88280922284da2784a01e90dc9ccd3be7d48bbe76ca0b8375ac0d3f0f312b1e19da181a18ed")
backend = service.least_busy(
    operational=True, simulator=False, min_num_qubits=127
)
 
print(backend.name)
ibm_brisbane
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
 
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pm.run(circuit)
print(f">>> Circuit ops (ISA): {isa_circuit.count_ops()}")
>>> Circuit ops (ISA): OrderedDict([('rz', 7), ('sx', 4), ('measure', 2), ('ecr', 1)])
 
sampler = Sampler(backend)
job = sampler.run([(isa_circuit)])
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
>>> Job ID: cx854z3pjw30008gxg70
>>> Job Status: QUEUED
result = job.result()
 
# Get results for the first (and only) PUB
pub_result = result[0]
print(
    f"Counts for the 'meas' output register: {pub_result.data.meas.get_counts()}"
)
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Cell In[52], line 1
----> 1 result = job.result()
      3 # Get results for the first (and only) PUB
      4 pub_result = result[0]

File ~/Library/Python/3.9/lib/python/site-packages/qiskit_ibm_runtime/runtime_job_v2.py:133, in result(self, timeout, decoder)
    115 def result(  # pylint: disable=arguments-differ
    116     self,
    117     timeout: Optional[float] = None,
    118     decoder: Optional[Type[ResultDecoder]] = None,
    119 ) -> Any:
    120     """Return the results of the job.
    121 
    122     Args:
    123         timeout: Number of seconds to wait for job.
    124         decoder: A :class:`ResultDecoder` subclass used to decode job results.
    125 
    126     Returns:
    127         Runtime job result.
    128 
    129     Raises:
    130         RuntimeJobFailureError: If the job failed.
    131         RuntimeJobMaxTimeoutError: If the job does not complete within given timeout.
    132         RuntimeInvalidStateError: If the job was cancelled, and attempting to retrieve result.
--> 133     """
    134     _decoder = decoder or self._final_result_decoder
    135     self.wait_for_final_state(timeout=timeout)

File ~/Library/Python/3.9/lib/python/site-packages/qiskit_ibm_runtime/runtime_job_v2.py:254, in wait_for_final_state(self, timeout)
    252 if self._status not in self.JOB_FINAL_STATES and not self._is_streaming():
    253     self._ws_client_future = self._executor.submit(self._start_websocket_client)
--> 254 if self._is_streaming():
    255     self._ws_client_future.result(timeout)
    256 # poll for status after stream has closed until status is final
    257 # because status doesn't become final as soon as stream closes

File /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/concurrent/futures/_base.py:440, in Future.result(self, timeout)
    437 elif self._state == FINISHED:
    438     return self.__get_result()
--> 440 self._condition.wait(timeout)
    442 if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
    443     raise CancelledError()

File /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py:312, in Condition.wait(self, timeout)
    310 try:    # restore state no matter what (e.g., KeyboardInterrupt)
    311     if timeout is None:
--> 312         waiter.acquire()
    313         gotit = True
    314     else:

KeyboardInterrupt: 
from qiskit_ibm_runtime import QiskitRuntimeService

service = QiskitRuntimeService(
    channel='ibm_quantum',
    instance='ibm-q/open/main',
    token='fbc77e68310da5c90990728b892ef5e327787a28a126ad837f8fb88280922284da2784a01e90dc9ccd3be7d48bbe76ca0b8375ac0d3f0f312b1e19da181a18ed'
)
job = service.job('cx7mq6wpx23g008bjceg')
job_result = job.result()

# To get counts for a particular pub result, use 
#
#pub_result = job_result[0].data.c.get_counts()
#
# where <idx> is the index of the pub and <classical register> is the name of the classical register. 
# You can use circuit.cregs to find the name of the classical registers.
job_result[0]
{'__type__': 'SamplerPubResult',
 '__value__': {'data': DataBin<>(meas=BitArray(<shape=(), num_shots=4096, num_bits=127>)),
  'metadata': {'circuit_metadata': {}}}}
base_runtime_job._start_websocket_client:WARNING:2024-12-04 08:49:38,208: An error occurred while streaming results from the server for job cx854z3pjw30008gxg70:
Traceback (most recent call last):
  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/qiskit_ibm_runtime/base_runtime_job.py", line 311, in _start_websocket_client
    def _start_websocket_client(self) -> None:
  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/qiskit_ibm_runtime/api/clients/runtime_ws.py", line 70, in job_results
    self.stream(url=url, retries=max_retries, backoff_factor=backoff_factor)
  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/qiskit_ibm_runtime/api/clients/base_websocket_client.py", line 222, in stream
    logger.info(error_message)
qiskit_ibm_runtime.api.exceptions.WebsocketError: 'Max retries exceeded: Failed to establish a websocket connection. Error: Traceback (most recent call last):\n  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/websocket/_http.py", line 154, in _get_addrinfo_list\n    addrinfo_list = socket.getaddrinfo(\n  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socket.py", line 953, in getaddrinfo\n    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):\nsocket.gaierror: [Errno 8] nodename nor servname provided, or not known\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/websocket/_app.py", line 418, in setSock\n    self.sock.connect(\n  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/websocket/_core.py", line 249, in connect\n    self.sock, addrs = connect(url, self.sock_opt, proxy_info(**options),\n  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/websocket/_http.py", line 121, in connect\n    addrinfo_list, need_tunnel, auth = _get_addrinfo_list(\n  File "/Users/butlerju/Library/Python/3.9/lib/python/site-packages/websocket/_http.py", line 166, in _get_addrinfo_list\n    raise WebSocketAddressException(e)\nwebsocket._exceptions.WebSocketAddressException: [Errno 8] nodename nor servname provided, or not known\n'
from qiskit_ibm_runtime import QiskitRuntimeService

service = QiskitRuntimeService(
    channel='ibm_quantum',
    instance='ibm-q/open/main',
    token='fbc77e68310da5c90990728b892ef5e327787a28a126ad837f8fb88280922284da2784a01e90dc9ccd3be7d48bbe76ca0b8375ac0d3f0f312b1e19da181a18ed'
)
job = service.job('cx854z3pjw30008gxg70')
job_result = job.result()

# To get counts for a particular pub result, use 
#
# pub_result = job_result[<idx>].data.<classical register>.get_counts()
#
# where <idx> is the index of the pub and <classical register> is the name of the classical register. 
# You can use circuit.cregs to find the name of the classical registers.
job_result
PrimitiveResult([{'__type__': 'SamplerPubResult', '__value__': {'data': DataBin<>(c=BitArray(<shape=(), num_shots=4096, num_bits=2>)), 'metadata': {'circuit_metadata': {}}}}], metadata={'execution': {'execution_spans': {'__type__': 'ExecutionSpanCollection', '__value__': {'spans': [{'__type__': 'ExecutionSpan', '__value__': {'start': datetime.datetime(2024, 12, 4, 17, 36, 36, 903488, tzinfo=tzutc()), 'stop': datetime.datetime(2024, 12, 4, 17, 36, 49, 928772, tzinfo=tzutc()), 'data_slices': {'0': [[4096], 0, 4096]}}}]}}}, 'version': 2})