Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Harmony backend for IonQ #49

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pennylane_ionq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
PennyLane IonQ overview
=======================
"""
from .device import SimulatorDevice, QPUDevice
from .device import SimulatorDevice, QPUDevice, HarmonyDevice
from ._version import __version__
16 changes: 12 additions & 4 deletions pennylane_ionq/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ class APIClient:
BASE_URL = "https://{}".format(HOSTNAME)

def __init__(self, **kwargs):
self.AUTHENTICATION_TOKEN = os.getenv("IONQ_API_KEY") or kwargs.get("api_key", None)
self.AUTHENTICATION_TOKEN = os.getenv("IONQ_API_KEY") or kwargs.get(
"api_key", None
)
self.DEBUG = False

if "IONQ_DEBUG" in os.environ:
Expand Down Expand Up @@ -220,7 +222,9 @@ def post(self, path, payload):
Returns:
requests.Response: A response object, or None if no response could be fetched
"""
return self.request(requests.post, url=self.join_path(path), data=json.dumps(payload))
return self.request(
requests.post, url=self.join_path(path), data=json.dumps(payload)
)


class ResourceManager:
Expand Down Expand Up @@ -259,7 +263,9 @@ def get(self, resource_id=None):
resource_id (int): the ID of an object to be retrieved
"""
if "GET" not in self.resource.SUPPORTED_METHODS:
raise MethodNotSupportedException("GET method on this resource is not supported")
raise MethodNotSupportedException(
"GET method on this resource is not supported"
)

if resource_id is not None:
response = self.client.get(self.join_path(str(resource_id)))
Expand All @@ -276,7 +282,9 @@ def create(self, **params):
**params: arbitrary parameters to be passed on to the POST request
"""
if "POST" not in self.resource.SUPPORTED_METHODS:
raise MethodNotSupportedException("POST method on this resource is not supported")
raise MethodNotSupportedException(
"POST method on this resource is not supported"
)

if self.resource.id:
raise ObjectAlreadyCreatedException("ID must be None when calling create")
Expand Down
43 changes: 38 additions & 5 deletions pennylane_ionq/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ class IonQDevice(QubitDevice):

def __init__(self, wires, *, target="simulator", shots=1024, api_key=None):
if shots is None:
raise ValueError("The ionq device does not support analytic expectation values.")
raise ValueError(
"The ionq device does not support analytic expectation values."
)

super().__init__(wires=wires, shots=shots)
self.target = target
Expand Down Expand Up @@ -116,7 +118,9 @@ def apply(self, operations, **kwargs):
rotations = kwargs.pop("rotations", [])

if len(operations) == 0 and len(rotations) == 0:
warnings.warn("Circuit is empty. Empty circuits return failures. Submitting anyway.")
warnings.warn(
"Circuit is empty. Empty circuits return failures. Submitting anyway."
)

for i, operation in enumerate(operations):
if i > 0 and operation.name in {"BasisState", "QubitStateVector"}:
Expand Down Expand Up @@ -188,7 +192,8 @@ def prob(self):
# Here, we rearrange the states to match the big-endian ordering
# expected by PennyLane.
basis_states = (
int(bin(int(k))[2:].rjust(self.num_wires, "0")[::-1], 2) for k in self.histogram
int(bin(int(k))[2:].rjust(self.num_wires, "0")[::-1], 2)
for k in self.histogram
)
idx = np.fromiter(basis_states, dtype=int)

Expand All @@ -204,7 +209,9 @@ def probability(self, wires=None, shot_range=None, bin_size=None):
if shot_range is None and bin_size is None:
return self.marginal_prob(self.prob, wires)

return self.estimate_probability(wires=wires, shot_range=shot_range, bin_size=bin_size)
return self.estimate_probability(
wires=wires, shot_range=shot_range, bin_size=bin_size
)


class SimulatorDevice(IonQDevice):
Expand Down Expand Up @@ -234,6 +241,7 @@ def generate_samples(self):
return QubitDevice.states_to_binary(samples, self.num_wires)


# deprecated("Prefer HarmonyDevice to fully specify generation.")
class QPUDevice(IonQDevice):
r"""QPU device for IonQ.

Expand Down Expand Up @@ -263,8 +271,33 @@ def generate_samples(self):
"""
number_of_states = 2**self.num_wires
counts = np.rint(
self.prob * self.shots, out=np.zeros(number_of_states, dtype=int), casting="unsafe"
self.prob * self.shots,
out=np.zeros(number_of_states, dtype=int),
casting="unsafe",
)
samples = np.repeat(np.arange(number_of_states), counts)
np.random.shuffle(samples)
return QubitDevice.states_to_binary(samples, self.num_wires)


class HarmonyDevice(QPUDevice):
r"""Harmony QPU device for IonQ.

Args:
wires (int or Iterable[Number, str]]): Number of wires to initialize the device with,
or iterable that contains unique labels for the subsystems as numbers (i.e., ``[-1, 0, 2]``)
or strings (``['ancilla', 'q1', 'q2']``).
shots (int, list[int]): Number of circuit evaluations/random samples used to estimate
expectation values of observables. If ``None``, the device calculates probability, expectation values,
and variances analytically. If an integer, it specifies the number of samples to estimate these quantities.
If a list of integers is passed, the circuit evaluations are batched over the list of shots.
api_key (str): The IonQ API key. If not provided, the environment
variable ``IONQ_API_KEY`` is used.
"""
name = "IonQ QPU PennyLane plugin"
short_name = "ionq.qpu.harmony"

def __init__(self, wires, *, shots=1024, api_key=None):
super().__init__(
wires=wires, target="qpu.harmony", shots=shots, api_key=api_key
)
5 changes: 3 additions & 2 deletions tests/test_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,11 @@ def test_failedcircuit(self, monkeypatch):
requests, "post", lambda url, timeout, data, headers: (url, data, headers)
)
monkeypatch.setattr(ResourceManager, "handle_response", lambda self, response: None)
monkeypatch.setattr(Job, "reload", lambda ignored: None)
monkeypatch.setattr(Job, "is_complete", False)
monkeypatch.setattr(Job, "is_failed", True)

dev = IonQDevice(wires=(0,))
dev = IonQDevice(wires=(0,), api_key="foo")
with pytest.raises(JobExecutionError):
dev._submit_job()

Expand Down