Skip to content
Merged
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
8 changes: 2 additions & 6 deletions cirq-ionq/cirq_ionq/calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def num_qubits(self) -> int:

def target(self) -> str:
"""The name of the QPU."""
return self._calibration_dict['target']
return self._calibration_dict['backend']

def calibration_time(self, tz: datetime.tzinfo | None = None) -> datetime.datetime:
"""Return a Python datetime object for the calibration time.
Expand All @@ -42,11 +42,7 @@ def calibration_time(self, tz: datetime.tzinfo | None = None) -> datetime.dateti
Returns:
A `datetime` object with the time.
"""
# Python datetime only like microseconds, not milliseconds, and does not like 'Z'.
first, second = self._calibration_dict['date'].split('.')
modified_date = f'{first}.{second[:3]}'
dt = datetime.datetime.strptime(modified_date, '%Y-%m-%dT%H:%M:%S.%f')
return dt.replace(tzinfo=datetime.timezone.utc).astimezone(tz=tz)
return datetime.datetime.fromisoformat(self._calibration_dict['date']).astimezone(tz=tz)

def fidelities(self) -> dict:
"""Returns the metrics (fidelities)."""
Expand Down
28 changes: 7 additions & 21 deletions cirq-ionq/cirq_ionq/calibration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
def test_calibration_fields():
calibration_dict = {
'connectivity': [[0, 1], [0, 2], [1, 2]],
'target': 'ionq.qpu',
'backend': 'qpu.forte-1',
'qubits': 3,
'fidelity': {'1q': {'mean': 0.999}, '2q': {'mean': 0.999}},
'fidelity': {'1q': {'median': 0.999}, '2q': {'median': 0.999}},
'timing': {'1q': 1.1e-05, '2q': 0.00021, 'readout': 0.000175, 'reset': 3.5e-05},
'date': '2020-08-07T12:47:22.337Z',
'date': '2020-08-07T12:47:22Z',
}
cal = ionq.Calibration(calibration_dict=calibration_dict)
assert cal.connectivity() == {
Expand All @@ -38,31 +38,17 @@ def test_calibration_fields():
(cirq.LineQubit(1), cirq.LineQubit(2)),
(cirq.LineQubit(2), cirq.LineQubit(1)),
}
assert cal.target() == 'ionq.qpu'
assert cal.target() == 'qpu.forte-1'
assert cal.num_qubits() == 3
assert cal.fidelities() == {'1q': {'mean': 0.999}, '2q': {'mean': 0.999}}
assert cal.fidelities() == {'1q': {'median': 0.999}, '2q': {'median': 0.999}}
assert cal.timings() == {'1q': 1.1e-05, '2q': 0.00021, 'readout': 0.000175, 'reset': 3.5e-05}
assert cal.calibration_time(tz=datetime.timezone.utc) == datetime.datetime(
year=2020,
month=8,
day=7,
hour=12,
minute=47,
second=22,
microsecond=337000,
tzinfo=datetime.timezone.utc,
year=2020, month=8, day=7, hour=12, minute=47, second=22, tzinfo=datetime.timezone.utc
)
time_minus_one = cal.calibration_time(tz=datetime.timezone(datetime.timedelta(hours=-2)))
# It's the same time...
assert time_minus_one == datetime.datetime(
year=2020,
month=8,
day=7,
hour=12,
minute=47,
second=22,
microsecond=337000,
tzinfo=datetime.timezone.utc,
year=2020, month=8, day=7, hour=12, minute=47, second=22, tzinfo=datetime.timezone.utc
)
# ...just has a different timezone.
assert time_minus_one.tzinfo == datetime.timezone(datetime.timedelta(hours=-2))
166 changes: 77 additions & 89 deletions cirq-ionq/cirq_ionq/ionq_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ class _IonQClient:
Users should not instantiate this themselves, but instead should use `cirq_ionq.Service`.
"""

SUPPORTED_TARGETS = {'qpu', 'simulator'}
SUPPORTED_VERSIONS = {'v0.4'}

def __init__(
Expand All @@ -82,8 +81,8 @@ def __init__(
besides the base scheme and netloc, i.e. it only takes the part of the host of
the form `http://example.com` of `http://example.com/test`.
api_key: The key used for authenticating against the IonQ API.
default_target: The default target to run against. Supports one of 'qpu' and
'simulator'. Can be overridden by calls with target in their signature.
default_target: The default target to run against, for example 'simulator' or
'qpu.forte-1'. Can be overridden by calls with target in their signature.
api_version: Which version of the api to use. As of June, 2025, accepts 'v0.4' only,
which is the default.
max_retry_seconds: The time to continue retriable responses. Defaults to 3600.
Expand All @@ -97,17 +96,13 @@ def __init__(
assert (
api_version in self.SUPPORTED_VERSIONS
), f'Only api v0.4 is accepted but was {api_version}'
assert (
default_target is None or default_target in self.SUPPORTED_TARGETS
), f'Target can only be one of {self.SUPPORTED_TARGETS} but was {default_target}.'
assert max_retry_seconds >= 0, 'Negative retry not possible without time machine.'

self.url = f'{url.scheme}://{url.netloc}/{api_version}'
self.headers = self.api_headers(api_key)
self.default_target = default_target
self.max_retry_seconds = max_retry_seconds
self.verbose = verbose
self.batch_mode = False

def create_job(
self,
Expand All @@ -126,8 +121,8 @@ def create_job(
repetitions: The number of times to repeat the circuit. For simulation the repeated
sampling is not done on the server, but is passed as metadata to be recovered
from the returned job.
target: If supplied the target to run on. Supports one of `qpu` or `simulator`. If not
set, uses `default_target`.
target: If supplied the target to run on, for example `simulator` or `qpu.forte-1`.
If not set, uses `default_target`.
name: An optional name of the job. Different than the `job_id` of the job.
extra_query_params: Specify any parameters to include in the request.
batch_mode: bool determines whether to submit a single circuit or a batch of circuits.
Expand All @@ -144,7 +139,6 @@ def create_job(
json: dict[str, Any] = {
'backend': actual_target,
"type": "ionq.multi-circuit.v1" if batch_mode else "ionq.circuit.v1",
'lang': 'json',
'input': serialized_program.input,
}
if name:
Expand All @@ -155,7 +149,7 @@ def create_job(
json['settings'] = serialized_program.settings

# Shots are ignored by simulator, but pass them anyway.
json['shots'] = str(repetitions)
json['shots'] = repetitions
# API does not return number of shots so pass this through as metadata.
json['metadata']['shots'] = str(repetitions)

Expand Down Expand Up @@ -185,10 +179,7 @@ def create_job(
def request():
return requests.post(f'{self.url}/jobs', json=json, headers=self.headers)

request_response = self._make_request(request, json).json()
self.batch_mode = batch_mode

return request_response
return self._make_request(request, json).json()

def get_job(self, job_id: str) -> dict:
"""Get the job from the IonQ API.
Expand All @@ -210,7 +201,11 @@ def request():
return self._make_request(request, {}).json()

def get_results(
self, job_id: str, sharpen: bool | None = None, extra_query_params: dict | None = None
self,
job_id: str,
sharpen: bool | None = None,
extra_query_params: dict | None = None,
batch_mode: bool = False,
):
"""Get job results from IonQ API.

Expand All @@ -219,6 +214,7 @@ def get_results(
sharpen: A Boolean that determines how to aggregate error mitigated.
If True, apply majority vote mitigation; if False, apply average mitigation.
extra_query_params: Specify any parameters to include in the request.
batch_mode: Whether the job is a batch of circuits rather than a single circuit.

Returns:
extra_query_paramsresponse as a dict.
Expand All @@ -236,42 +232,50 @@ def get_results(
if extra_query_params:
params.update(extra_query_params)

suffix = '/aggregated' if batch_mode else ''

def request():
if self.batch_mode:
return requests.get(
f'{self.url}/jobs/{job_id}/results/probabilities/aggregated',
params=params,
headers=self.headers,
)
elif not self.batch_mode:
return requests.get(
f'{self.url}/jobs/{job_id}/results/probabilities',
params=params,
headers=self.headers,
)
return requests.get(
f'{self.url}/jobs/{job_id}/results/probabilities{suffix}',
params=params,
headers=self.headers,
)

return self._make_request(request, {}).json()

def list_jobs(
self, status: str | None = None, limit: int = 100, batch_size: int = 1000
self, status: str | None = None, limit: int = 100, batch_size: int = 250
) -> list[dict[str, Any]]:
"""Lists jobs from the IonQ API.

Args:
status: If not None, filter to jobs with this status.
limit: The maximum number of jobs to return.
batch_size: The size of the batches requested per HTTP GET call.
batch_size: The number of jobs requested per HTTP GET call, at most 250.

Returns:
A list of the JSON bodies of the job dicts.

Raises:
IonQException: If the API call fails.
"""
params = {}
params: dict[str, Any] = {}
if status:
params['status'] = status
return self._list('jobs', params, 'jobs', limit, batch_size)
jobs: list[dict[str, Any]] = []
while len(jobs) < limit:
# The API returns at most 250 jobs per page.
params = {**params, 'limit': min(batch_size, limit - len(jobs), 250)}

def request():
return requests.get(f'{self.url}/jobs', headers=self.headers, params=params)

response = self._make_request(request, {}).json()
jobs.extend(response['jobs'])
if not response.get('next'):
break
params = {**params, 'next': response['next']}
return jobs[:limit]

def cancel_job(self, job_id: str) -> dict:
"""Cancel a job on the IonQ API.
Expand Down Expand Up @@ -306,46 +310,69 @@ def request():

return self._make_request(request, {}).json()

def get_current_calibration(self) -> dict:
"""Returns the current calibration as an `cirq_ionq.Calibration` object.
def get_current_calibration(self, target: str | None = None) -> dict:
"""Returns the most recent calibration of a QPU.

Currently returns the current calibration for the only target `qpu`.
"""
Args:
target: The QPU to get the calibration of. If not set, uses `default_target`.

def request():
return requests.get(f'{self.url}/calibrations/current', headers=self.headers)
Returns:
The JSON body of the calibration as a dict.

return self._make_request(request, {}).json()
Raises:
IonQNotFoundException: If the target has no calibrations, as for the simulator.
IonQException: For other API call failures.
"""
calibrations = self.list_calibrations(limit=1, target=target)
if not calibrations:
raise ionq_exceptions.IonQNotFoundException(
f'IonQ has no calibrations for target {self._target(target)}.'
)
return calibrations[0]

def list_calibrations(
self,
start: datetime.datetime | None = None,
end: datetime.datetime | None = None,
limit: int = 100,
batch_size: int = 1000,
*,
target: str | None = None,
) -> list[dict]:
"""Lists calibrations from the IonQ API.
"""Lists calibrations of a QPU from the IonQ API, most recent first.

Args:
start: If supplied, only calibrations after this date and time. Accurate to seconds.
end: If supplied, only calibrations before this date and time. Accurate to seconds.
start: If supplied, only calibrations from this day or later.
end: If supplied, only calibrations from this day or earlier.
limit: The maximum number of calibrations to return.
batch_size: The size of the batches requested per HTTP GET call.
target: The QPU to list calibrations of. If not set, uses `default_target`.

Returns:
A list of the JSON bodies of the calibration dicts.

Raises:
IonQException: If the API call fails.
"""

params = {}
epoch = datetime.datetime.fromtimestamp(0, datetime.UTC)
url = f'{self.url}/backends/{self._target(target)}/characterizations'
# The API returns at most 10 calibrations per page.
params: dict[str, Any] = {'limit': min(limit, 10)}
if start:
params['start'] = int((start - epoch).total_seconds() * 1000)
params['start'] = start.astimezone(datetime.UTC).date().isoformat()
if end:
params['end'] = int((end - epoch).total_seconds() * 1000)
return self._list('calibrations', params, 'calibrations', limit, batch_size)
params['end'] = end.astimezone(datetime.UTC).date().isoformat()
calibrations: list[dict] = []
page = 1
while len(calibrations) < limit:

def request():
return requests.get(url, headers=self.headers, params={**params, 'page': page})

response = self._make_request(request, {}).json()
# The API returns null rather than an empty list.
calibrations.extend(response['characterizations'] or [])
if page >= response['pages']:
break
page += 1
return calibrations[:limit]

def api_headers(self, api_key: str):
"""API Headers needed to make calls to the REST API.
Expand Down Expand Up @@ -450,42 +477,3 @@ def _make_request(
print(f'Waiting {delay_seconds} seconds before retrying.')
time.sleep(delay_seconds)
delay_seconds *= 2

def _list(
self, resource_path: str, params: dict, response_key: str, limit: int, batch_size: int
) -> list[dict]:
"""Helper method for list calls.

Args:
resource_path: The resource path for the object being listed. Follows the base URL
and version. No leading slash.
params: The params to pass with the list call.
response_key: The key to get the list of objects that have been listed.
limit: The maximum number of objects to return.
batch_size: The size of the batches requested per HTTP GET call.

Returns:
A sequence of dictionaries corresponding to the objects listed.
"""
json = {'limit': batch_size}
token: str | None = None
results: list[dict[str, Any]] = []
while len(results) < limit:
full_params = params.copy()
if token:
full_params['next'] = token

def request():
return requests.get(
f'{self.url}/{resource_path}',
headers=self.headers,
json=json,
params=full_params,
)

response = self._make_request(request, json).json()
results.extend(response[response_key])
if 'next' not in response:
break
token = response['next']
return results[:limit]
Loading
Loading