Skip to content

Commit

Permalink
Merge pull request #191 from basnijholt/typing
Browse files Browse the repository at this point in the history
Add type annotations to part of the public API
  • Loading branch information
Cynocracy authored Sep 9, 2024
2 parents 95788ad + ff931a0 commit e66e6f6
Show file tree
Hide file tree
Showing 12 changed files with 156 additions and 87 deletions.
13 changes: 11 additions & 2 deletions qiskit_ionq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@

"""Provider for IonQ backends"""

import warnings

# warn if qiskit is not installed
try:
from qiskit.version import get_version_info # pylint: disable=unused-import
Expand All @@ -41,3 +39,14 @@
from .ionq_gates import GPIGate, GPI2Gate, MSGate, ZZGate
from .constants import ErrorMitigation
from .ionq_equivalence_library import add_equivalences

__all__ = [
"__version__",
"IonQProvider",
"GPIGate",
"GPI2Gate",
"MSGate",
"ZZGate",
"ErrorMitigation",
"add_equivalences",
]
16 changes: 10 additions & 6 deletions qiskit_ionq/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
# limitations under the License.

"""Exceptions for the IonQ Provider."""
from __future__ import annotations

from typing import Literal

import json.decoder as jd

import requests
Expand All @@ -36,10 +40,10 @@
class IonQError(QiskitError):
"""Base class for errors raised by an IonQProvider."""

def __str__(self):
def __str__(self) -> str:
return f"{self.__class__.__name__}({self.message!r})"

def __repr__(self):
def __repr__(self) -> str:
return repr(str(self))


Expand Down Expand Up @@ -94,7 +98,7 @@ class IonQAPIError(IonQError):
"""

@classmethod
def raise_for_status(cls, response):
def raise_for_status(cls, response) -> IonQAPIError:
"""Raise an instance of the exception class from an API response object if needed.
Args:
response (:class:`Response <requests.Response>`): An IonQ REST API response.
Expand All @@ -111,7 +115,7 @@ def raise_for_status(cls, response):
raise res

@classmethod
def from_response(cls, response):
def from_response(cls, response: requests.Response) -> IonQAPIError:
"""Raise an instance of the exception class from an API response object.
Args:
Expand Down Expand Up @@ -187,7 +191,7 @@ class IonQGateError(IonQError, JobError):
gate_name: The name of the gate which caused this error.
"""

def __init__(self, gate_name, gateset):
def __init__(self, gate_name: str, gateset: Literal["qis", "native"]):
self.gate_name = gate_name
self.gateset = gateset
super().__init__(
Expand All @@ -210,7 +214,7 @@ class IonQMidCircuitMeasurementError(IonQError, JobError):
qubit_index: The qubit index to be measured mid-circuit
"""

def __init__(self, qubit_index, gate_name):
def __init__(self, qubit_index: int, gate_name: str):
self.qubit_index = qubit_index
self.gate_name = gate_name
super().__init__(
Expand Down
26 changes: 18 additions & 8 deletions qiskit_ionq/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,25 @@
to IonQ REST API compatible values.
"""

from __future__ import annotations

import json
import gzip
import base64
import platform
import warnings
import os
from typing import Literal
import requests
from dotenv import dotenv_values

from qiskit import __version__ as qiskit_terra_version
from qiskit.circuit import controlledgate as q_cgates
from qiskit.circuit import (
controlledgate as q_cgates,
QuantumCircuit,
QuantumRegister,
ClassicalRegister,
)
from qiskit.circuit.library import standard_gates as q_gates

# Use this to get version instead of __version__ to avoid circular dependency.
Expand Down Expand Up @@ -133,7 +141,9 @@
}


def qiskit_circ_to_ionq_circ(input_circuit, gateset="qis"):
def qiskit_circ_to_ionq_circ(
input_circuit: QuantumCircuit, gateset: Literal["qis", "native"] = "qis"
):
"""Build a circuit in IonQ's instruction format from qiskit instructions.
.. ATTENTION:: This function ignores the following compiler directives:
Expand Down Expand Up @@ -273,7 +283,9 @@ def qiskit_circ_to_ionq_circ(input_circuit, gateset="qis"):
return output_circuit, num_meas, meas_map


def get_register_sizes_and_labels(registers):
def get_register_sizes_and_labels(
registers: list[QuantumRegister | ClassicalRegister],
) -> tuple[list, list]:
"""Returns a tuple of sizes and labels in for a given register
Args:
Expand All @@ -299,7 +311,7 @@ def get_register_sizes_and_labels(registers):
return sizes, labels


def compress_to_metadata_string(metadata): # pylint: disable=invalid-name
def compress_to_metadata_string(metadata: dict | list) -> str: # pylint: disable=invalid-name
"""
Convert a metadata object to a compact string format (dumped, gzipped, base64 encoded)
for storing in IonQ API metadata
Expand All @@ -318,7 +330,7 @@ def compress_to_metadata_string(metadata): # pylint: disable=invalid-name
return encoded.decode()


def decompress_metadata_string(input_string): # pylint: disable=invalid-name
def decompress_metadata_string(input_string: str) -> dict | list: # pylint: disable=invalid-name
"""
Convert compact string format (dumped, gzipped, base64 encoded) from
IonQ API metadata back into a dict or list of dicts relevant to building
Expand Down Expand Up @@ -366,7 +378,7 @@ def qiskit_to_ionq(
else:
ionq_circs, _, meas_map = qiskit_circ_to_ionq_circ(circuit, backend.gateset())
circuit = [circuit]

circuit: list[QuantumCircuit] | tuple[QuantumCircuit, ...]
metadata_list = [
{
"memory_slots": circ.num_clbits, # int
Expand Down Expand Up @@ -479,7 +491,6 @@ def default(self, o):
return "unknown"



def resolve_credentials(token: str = None, url: str = None):
"""Resolve credentials for use in IonQ API calls.
Expand Down Expand Up @@ -516,7 +527,6 @@ def resolve_credentials(token: str = None, url: str = None):
}



def get_n_qubits(backend: str, _fallback=100) -> int:
"""Get the number of qubits for a given backend.
Expand Down
Loading

0 comments on commit e66e6f6

Please sign in to comment.