diff --git a/cirq-ionq/cirq_ionq/calibration.py b/cirq-ionq/cirq_ionq/calibration.py index f1b4b1332f..68b78f7c0f 100644 --- a/cirq-ionq/cirq_ionq/calibration.py +++ b/cirq-ionq/cirq_ionq/calibration.py @@ -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. @@ -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).""" diff --git a/cirq-ionq/cirq_ionq/calibration_test.py b/cirq-ionq/cirq_ionq/calibration_test.py index 661bddb619..007620012f 100644 --- a/cirq-ionq/cirq_ionq/calibration_test.py +++ b/cirq-ionq/cirq_ionq/calibration_test.py @@ -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() == { @@ -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)) diff --git a/cirq-ionq/cirq_ionq/ionq_client.py b/cirq-ionq/cirq_ionq/ionq_client.py index d315ce37fc..fde71946e7 100644 --- a/cirq-ionq/cirq_ionq/ionq_client.py +++ b/cirq-ionq/cirq_ionq/ionq_client.py @@ -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__( @@ -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. @@ -97,9 +96,6 @@ 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}' @@ -107,7 +103,6 @@ def __init__( self.default_target = default_target self.max_retry_seconds = max_retry_seconds self.verbose = verbose - self.batch_mode = False def create_job( self, @@ -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. @@ -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: @@ -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) @@ -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. @@ -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. @@ -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. @@ -236,31 +232,26 @@ 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. @@ -268,10 +259,23 @@ def list_jobs( 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. @@ -306,31 +310,41 @@ 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. @@ -338,14 +352,27 @@ def list_calibrations( 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. @@ -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] diff --git a/cirq-ionq/cirq_ionq/ionq_client_test.py b/cirq-ionq/cirq_ionq/ionq_client_test.py index dad5b425e8..aeda5d35ec 100644 --- a/cirq-ionq/cirq_ionq/ionq_client_test.py +++ b/cirq-ionq/cirq_ionq/ionq_client_test.py @@ -55,17 +55,6 @@ def test_ionq_client_invalid_api_version(): ) -def test_ionq_client_invalid_target(): - with pytest.raises(AssertionError, match='the store'): - _ = ionq.ionq_client._IonQClient( - remote_host='http://example.com', api_key='a', default_target='the store' - ) - with pytest.raises(AssertionError, match='Target'): - _ = ionq.ionq_client._IonQClient( - remote_host='http://example.com', api_key='a', default_target='the store' - ) - - def test_ionq_client_time_travel(): with pytest.raises(AssertionError, match='time machine'): _ = ionq.ionq_client._IonQClient( @@ -77,7 +66,7 @@ def test_ionq_client_attributes(): client = ionq.ionq_client._IonQClient( remote_host='http://example.com', api_key='to_my_heart', - default_target='qpu', + default_target='qpu.forte-1', max_retry_seconds=10, verbose=True, ) @@ -88,7 +77,7 @@ def test_ionq_client_attributes(): 'User-Agent': client._user_agent(), } assert client.headers['User-Agent'].startswith('cirq/') - assert client.default_target == 'qpu' + assert client.default_target == 'qpu.forte-1' assert client.max_retry_seconds == 10 assert client.verbose is True @@ -116,7 +105,6 @@ def test_ionq_client_create_job(mock_post): expected_json = { 'backend': 'qpu', 'type': 'ionq.circuit.v1', - 'lang': 'json', 'input': {'job': 'mine'}, 'name': 'bacon', 'metadata': {'shots': '200', 'a': '0,1'}, @@ -127,7 +115,7 @@ def test_ionq_client_create_job(mock_post): }, 'noise': {"model": "aria-1", "seed": 7}, 'dry_run': True, - 'shots': '200', + 'shots': 200, } expected_headers = { 'Authorization': 'apiKey to_my_heart', @@ -166,10 +154,9 @@ def test_ionq_client_create_job_error_mitigation_is_correctly_initialized(mock_p expected_json = { 'backend': 'qpu', 'type': 'ionq.circuit.v1', - 'lang': 'json', 'input': {'job': 'mine'}, 'name': 'bacon', - 'shots': '200', + 'shots': 200, 'key': 'value', 'metadata': {'shots': '200', 'a': '0,1'}, 'settings': {'error_mitigation': {'debiasing': True}}, @@ -211,10 +198,9 @@ def test_ionq_client_create_job_compilation_is_correctly_initialized(mock_post): expected_json = { 'backend': 'qpu', 'type': 'ionq.circuit.v1', - 'lang': 'json', 'input': {'job': 'mine'}, 'name': 'bacon', - 'shots': '200', + 'shots': 200, 'key': 'value', 'metadata': {'shots': '200', 'a': '0,1'}, 'settings': {'compilation': {"opt": 3, "precision": "1E-4"}}, @@ -256,10 +242,9 @@ def test_ionq_client_create_job_extra_params(mock_post): expected_json = { 'backend': 'qpu', 'type': 'ionq.circuit.v1', - 'lang': 'json', 'input': {'job': 'mine'}, 'name': 'bacon', - 'shots': '200', + 'shots': 200, 'key': 'value', 'metadata': {'shots': '200', 'a': '0,1'}, } @@ -600,7 +585,6 @@ def test_ionq_client_get_results(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.return_value = {'foo': 'bar'} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - client.batch_mode = False response = client.get_results(job_id='job_id', sharpen=False) assert response == {'foo': 'bar'} @@ -621,8 +605,7 @@ def test_ionq_client_get_results_batch_mode(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.return_value = {'foo': 'bar'} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - client.batch_mode = True - response = client.get_results(job_id='job_id', sharpen=False) + response = client.get_results(job_id='job_id', sharpen=False, batch_mode=True) assert response == {'foo': 'bar'} expected_headers = { @@ -642,7 +625,6 @@ def test_ionq_client_get_results_extra_params(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.return_value = {'foo': 'bar'} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - client.batch_mode = False response = client.get_results(job_id='job_id', extra_query_params={'sharpen': False}) assert response == {'foo': 'bar'} @@ -663,8 +645,9 @@ def test_ionq_client_get_results_extra_params_batch_mode(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.return_value = {'foo': 'bar'} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - client.batch_mode = True - response = client.get_results(job_id='job_id', extra_query_params={'sharpen': False}) + response = client.get_results( + job_id='job_id', extra_query_params={'sharpen': False}, batch_mode=True + ) assert response == {'foo': 'bar'} expected_headers = { @@ -682,7 +665,7 @@ def test_ionq_client_get_results_extra_params_batch_mode(mock_get): @mock.patch('requests.get') def test_ionq_client_list_jobs(mock_get): mock_get.return_value.ok = True - mock_get.return_value.json.return_value = {'jobs': [{'id': '1'}, {'id': '2'}]} + mock_get.return_value.json.return_value = {'jobs': [{'id': '1'}, {'id': '2'}], 'next': None} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') response = client.list_jobs() assert response == [{'id': '1'}, {'id': '2'}] @@ -693,14 +676,14 @@ def test_ionq_client_list_jobs(mock_get): 'User-Agent': client._user_agent(), } mock_get.assert_called_with( - 'http://example.com/v0.4/jobs', headers=expected_headers, json={'limit': 1000}, params={} + 'http://example.com/v0.4/jobs', headers=expected_headers, params={'limit': 100} ) @mock.patch('requests.get') def test_ionq_client_list_jobs_status(mock_get): mock_get.return_value.ok = True - mock_get.return_value.json.return_value = {'jobs': [{'id': '1'}, {'id': '2'}]} + mock_get.return_value.json.return_value = {'jobs': [{'id': '1'}, {'id': '2'}], 'next': None} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') response = client.list_jobs(status='canceled') assert response == [{'id': '1'}, {'id': '2'}] @@ -713,15 +696,17 @@ def test_ionq_client_list_jobs_status(mock_get): mock_get.assert_called_with( 'http://example.com/v0.4/jobs', headers=expected_headers, - json={'limit': 1000}, - params={'status': 'canceled'}, + params={'limit': 100, 'status': 'canceled'}, ) @mock.patch('requests.get') def test_ionq_client_list_jobs_limit(mock_get): mock_get.return_value.ok = True - mock_get.return_value.json.return_value = {'jobs': [{'id': '1'}, {'id': '2'}, {'id': 3}]} + mock_get.return_value.json.return_value = { + 'jobs': [{'id': '1'}, {'id': '2'}, {'id': 3}], + 'next': None, + } client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') response = client.list_jobs(limit=2) assert response == [{'id': '1'}, {'id': '2'}] @@ -732,17 +717,26 @@ def test_ionq_client_list_jobs_limit(mock_get): 'User-Agent': client._user_agent(), } mock_get.assert_called_with( - 'http://example.com/v0.4/jobs', headers=expected_headers, json={'limit': 1000}, params={} + 'http://example.com/v0.4/jobs', headers=expected_headers, params={'limit': 2} ) +@mock.patch('requests.get') +def test_ionq_client_list_jobs_batch_size_capped(mock_get): + mock_get.return_value.ok = True + mock_get.return_value.json.return_value = {'jobs': [], 'next': None} + client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') + client.list_jobs(limit=1000, batch_size=1000) + assert mock_get.call_args.kwargs['params'] == {'limit': 250} + + @mock.patch('requests.get') def test_ionq_client_list_jobs_batches(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.side_effect = [ {'jobs': [{'id': '1'}], 'next': 'a'}, {'jobs': [{'id': '2'}], 'next': 'b'}, - {'jobs': [{'id': '3'}]}, + {'jobs': [{'id': '3'}], 'next': None}, ] client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') response = client.list_jobs(batch_size=1) @@ -756,11 +750,11 @@ def test_ionq_client_list_jobs_batches(mock_get): url = 'http://example.com/v0.4/jobs' mock_get.assert_has_calls( [ - mock.call(url, headers=expected_headers, json={'limit': 1}, params={}), + mock.call(url, headers=expected_headers, params={'limit': 1}), mock.call().json(), - mock.call(url, headers=expected_headers, json={'limit': 1}, params={'next': 'a'}), + mock.call(url, headers=expected_headers, params={'limit': 1, 'next': 'a'}), mock.call().json(), - mock.call(url, headers=expected_headers, json={'limit': 1}, params={'next': 'b'}), + mock.call(url, headers=expected_headers, params={'limit': 1, 'next': 'b'}), mock.call().json(), ] ) @@ -774,7 +768,7 @@ def test_ionq_client_list_jobs_batches_does_not_divide_total(mock_get): {'jobs': [{'id': '3'}]}, ] client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - response = client.list_jobs(batch_size=2) + response = client.list_jobs(limit=3, batch_size=2) assert response == [{'id': '1'}, {'id': '2'}, {'id': '3'}] expected_headers = { @@ -785,9 +779,9 @@ def test_ionq_client_list_jobs_batches_does_not_divide_total(mock_get): url = 'http://example.com/v0.4/jobs' mock_get.assert_has_calls( [ - mock.call(url, headers=expected_headers, json={'limit': 2}, params={}), + mock.call(url, headers=expected_headers, params={'limit': 2}), mock.call().json(), - mock.call(url, headers=expected_headers, json={'limit': 2}, params={'next': 'a'}), + mock.call(url, headers=expected_headers, params={'limit': 1, 'next': 'a'}), mock.call().json(), ] ) @@ -819,6 +813,7 @@ def test_ionq_client_list_jobs_retry(mock_get): response1.ok = False response1.status_code = requests.codes.service_unavailable response2.ok = True + response2.json.return_value = {'jobs': [], 'next': None} client = ionq.ionq_client._IonQClient( remote_host='http://example.com', api_key='to_my_heart', default_target='simulator' ) @@ -965,18 +960,20 @@ def test_ionq_client_delete_job_retry(mock_put): @mock.patch('requests.get') def test_ionq_client_get_current_calibrations(mock_get): mock_get.return_value.ok = True - mock_get.return_value.json.return_value = {'foo': 'bar'} + mock_get.return_value.json.return_value = {'characterizations': [{'id': '1'}], 'pages': 5} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - response = client.get_current_calibration() - assert response == {'foo': 'bar'} + response = client.get_current_calibration(target='qpu.forte-1') + assert response == {'id': '1'} expected_headers = { 'Authorization': 'apiKey to_my_heart', 'Content-Type': 'application/json', 'User-Agent': client._user_agent(), } - mock_get.assert_called_with( - 'http://example.com/v0.4/calibrations/current', headers=expected_headers + mock_get.assert_called_once_with( + 'http://example.com/v0.4/backends/qpu.forte-1/characterizations', + headers=expected_headers, + params={'limit': 1, 'page': 1}, ) @@ -987,16 +984,18 @@ def test_ionq_client_get_current_calibration_unauthorized(mock_get): client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') with pytest.raises(ionq.IonQException, match='Not authorized'): - _ = client.get_current_calibration() + _ = client.get_current_calibration(target='qpu.forte-1') @mock.patch('requests.get') def test_ionq_client_get_current_calibration_not_found(mock_get): - (mock_get.return_value).ok = False - (mock_get.return_value).status_code = requests.codes.not_found + mock_get.return_value.ok = True + mock_get.return_value.json.return_value = {'characterizations': None, 'pages': 0} - client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - with pytest.raises(ionq.IonQNotFoundException, match='not find'): + client = ionq.ionq_client._IonQClient( + remote_host='http://example.com', api_key='to_my_heart', default_target='simulator' + ) + with pytest.raises(ionq.IonQNotFoundException, match='no calibrations for target simulator'): _ = client.get_current_calibration() @@ -1007,7 +1006,7 @@ def test_ionq_client_get_current_calibration_not_retriable(mock_get): client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') with pytest.raises(ionq.IonQException, match='Status: 501'): - _ = client.get_current_calibration() + _ = client.get_current_calibration(target='qpu.forte-1') @mock.patch('requests.get') @@ -1018,17 +1017,21 @@ def test_ionq_client_get_calibration_retry(mock_get): response1.ok = False response1.status_code = requests.codes.service_unavailable response2.ok = True + response2.json.return_value = {'characterizations': [{'id': '1'}], 'pages': 1} client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - _ = client.get_current_calibration() + _ = client.get_current_calibration(target='qpu.forte-1') assert mock_get.call_count == 2 @mock.patch('requests.get') def test_ionq_client_list_calibrations(mock_get): mock_get.return_value.ok = True - mock_get.return_value.json.return_value = {'calibrations': [{'id': '1'}, {'id': '2'}]} + mock_get.return_value.json.return_value = { + 'characterizations': [{'id': '1'}, {'id': '2'}], + 'pages': 1, + } client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - response = client.list_calibrations() + response = client.list_calibrations(target='qpu.forte-1') assert response == [{'id': '1'}, {'id': '2'}] expected_headers = { @@ -1037,21 +1040,24 @@ def test_ionq_client_list_calibrations(mock_get): 'User-Agent': client._user_agent(), } mock_get.assert_called_with( - 'http://example.com/v0.4/calibrations', + 'http://example.com/v0.4/backends/qpu.forte-1/characterizations', headers=expected_headers, - json={'limit': 1000}, - params={}, + params={'limit': 10, 'page': 1}, ) @mock.patch('requests.get') def test_ionq_client_list_calibrations_dates(mock_get): mock_get.return_value.ok = True - mock_get.return_value.json.return_value = {'calibrations': [{'id': '1'}, {'id': '2'}]} + mock_get.return_value.json.return_value = { + 'characterizations': [{'id': '1'}, {'id': '2'}], + 'pages': 1, + } client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') response = client.list_calibrations( start=datetime.datetime.fromtimestamp(1284286794, datetime.UTC), end=datetime.datetime.fromtimestamp(1284286795, datetime.UTC), + target='qpu.forte-1', ) assert response == [{'id': '1'}, {'id': '2'}] @@ -1061,10 +1067,9 @@ def test_ionq_client_list_calibrations_dates(mock_get): 'User-Agent': client._user_agent(), } mock_get.assert_called_with( - 'http://example.com/v0.4/calibrations', + 'http://example.com/v0.4/backends/qpu.forte-1/characterizations', headers=expected_headers, - json={'limit': 1000}, - params={'start': 1284286794000, 'end': 1284286795000}, + params={'limit': 10, 'page': 1, 'start': '2010-09-12', 'end': '2010-09-12'}, ) @@ -1072,10 +1077,11 @@ def test_ionq_client_list_calibrations_dates(mock_get): def test_ionq_client_list_calibrations_limit(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.return_value = { - 'calibrations': [{'id': '1'}, {'id': '2'}, {'id': 3}] + 'characterizations': [{'id': '1'}, {'id': '2'}], + 'pages': 3, } client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - response = client.list_calibrations(limit=2) + response = client.list_calibrations(limit=2, target='qpu.forte-1') assert response == [{'id': '1'}, {'id': '2'}] expected_headers = { @@ -1083,24 +1089,23 @@ def test_ionq_client_list_calibrations_limit(mock_get): 'Content-Type': 'application/json', 'User-Agent': client._user_agent(), } - mock_get.assert_called_with( - 'http://example.com/v0.4/calibrations', + mock_get.assert_called_once_with( + 'http://example.com/v0.4/backends/qpu.forte-1/characterizations', headers=expected_headers, - json={'limit': 1000}, - params={}, + params={'limit': 2, 'page': 1}, ) @mock.patch('requests.get') -def test_ionq_client_list_calibrations_batches(mock_get): +def test_ionq_client_list_calibrations_pages(mock_get): mock_get.return_value.ok = True mock_get.return_value.json.side_effect = [ - {'calibrations': [{'id': '1'}], 'next': 'a'}, - {'calibrations': [{'id': '2'}], 'next': 'b'}, - {'calibrations': [{'id': '3'}]}, + {'characterizations': [{'id': '1'}], 'pages': 3}, + {'characterizations': [{'id': '2'}], 'pages': 3}, + {'characterizations': [{'id': '3'}], 'pages': 3}, ] client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - response = client.list_calibrations(batch_size=1) + response = client.list_calibrations(target='qpu.forte-1') assert response == [{'id': '1'}, {'id': '2'}, {'id': '3'}] expected_headers = { @@ -1108,41 +1113,14 @@ def test_ionq_client_list_calibrations_batches(mock_get): 'Content-Type': 'application/json', 'User-Agent': client._user_agent(), } - url = 'http://example.com/v0.4/calibrations' + url = 'http://example.com/v0.4/backends/qpu.forte-1/characterizations' mock_get.assert_has_calls( [ - mock.call(url, headers=expected_headers, json={'limit': 1}, params={}), - mock.call().json(), - mock.call(url, headers=expected_headers, json={'limit': 1}, params={'next': 'a'}), + mock.call(url, headers=expected_headers, params={'limit': 10, 'page': 1}), mock.call().json(), - mock.call(url, headers=expected_headers, json={'limit': 1}, params={'next': 'b'}), - mock.call().json(), - ] - ) - - -@mock.patch('requests.get') -def test_ionq_client_list_calibrations_batches_does_not_divide_total(mock_get): - mock_get.return_value.ok = True - mock_get.return_value.json.side_effect = [ - {'calibrations': [{'id': '1'}, {'id': '2'}], 'next': 'a'}, - {'calibrations': [{'id': '3'}]}, - ] - client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') - response = client.list_calibrations(batch_size=2) - assert response == [{'id': '1'}, {'id': '2'}, {'id': '3'}] - - expected_headers = { - 'Authorization': 'apiKey to_my_heart', - 'Content-Type': 'application/json', - 'User-Agent': client._user_agent(), - } - url = 'http://example.com/v0.4/calibrations' - mock_get.assert_has_calls( - [ - mock.call(url, headers=expected_headers, json={'limit': 2}, params={}), + mock.call(url, headers=expected_headers, params={'limit': 10, 'page': 2}), mock.call().json(), - mock.call(url, headers=expected_headers, json={'limit': 2}, params={'next': 'a'}), + mock.call(url, headers=expected_headers, params={'limit': 10, 'page': 3}), mock.call().json(), ] ) @@ -1154,7 +1132,7 @@ def test_ionq_client_list_calibrations_unauthorized(mock_get): mock_get.return_value.status_code = requests.codes.unauthorized client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') with pytest.raises(ionq.IonQException, match='Not authorized'): - _ = client.list_calibrations() + _ = client.list_calibrations(target='qpu.forte-1') @mock.patch('requests.get') @@ -1163,7 +1141,7 @@ def test_ionq_client_list_calibrations_not_retriable(mock_get): mock_get.return_value.status_code = requests.codes.not_implemented client = ionq.ionq_client._IonQClient(remote_host='http://example.com', api_key='to_my_heart') with pytest.raises(ionq.IonQException, match='Status: 501'): - _ = client.list_calibrations() + _ = client.list_calibrations(target='qpu.forte-1') @mock.patch('requests.get') @@ -1174,6 +1152,7 @@ def test_ionq_client_list_calibrations_retry(mock_get): response1.ok = False response1.status_code = requests.codes.service_unavailable response2.ok = True + response2.json.return_value = {'characterizations': None, 'pages': 0} client = ionq.ionq_client._IonQClient( remote_host='http://example.com', api_key='to_my_heart', default_target='simulator' ) @@ -1189,6 +1168,7 @@ def test_ionq_client_list_calibrations_retry_nonstandard_error(mock_get): response1.ok = False response1.status_code = 524 response2.ok = True + response2.json.return_value = {'characterizations': None, 'pages': 0} client = ionq.ionq_client._IonQClient( remote_host='http://example.com', api_key='to_my_heart', default_target='simulator' ) diff --git a/cirq-ionq/cirq_ionq/job.py b/cirq-ionq/cirq_ionq/job.py index 2da2df11cb..f91efcfa7d 100644 --- a/cirq-ionq/cirq_ionq/job.py +++ b/cirq-ionq/cirq_ionq/job.py @@ -17,7 +17,6 @@ import json import time -import warnings from collections.abc import Sequence from typing import TYPE_CHECKING @@ -53,7 +52,7 @@ class Job: '(subsequent calls will return not found).', ) - NON_TERMINAL_STATES = ('ready', 'submitted', 'running') + NON_TERMINAL_STATES = ('ready', 'submitted', 'started') document( NON_TERMINAL_STATES, 'States of the IonQ API job which can transition to other states.' ) @@ -116,7 +115,7 @@ def target(self) -> str: """Returns the target where the job is to be run, or was run. Returns: - 'qpu' or 'simulator' depending on where the job was run or is running. + Where the job was run or is running, for example 'simulator' or 'qpu.forte-1'. Raises: IonQUnsuccessfulJob: If the job has failed, been canceled, or deleted. @@ -243,27 +242,24 @@ def results( break time.sleep(polling_seconds) time_waited_seconds += polling_seconds - if 'warning' in self._job and 'messages' in self._job['warning']: - for warning in self._job['warning']['messages']: - warnings.warn(warning) if self.status() != 'completed': - if 'failure' in self._job and 'error' in self._job['failure']: - error = self._job['failure']['error'] - raise RuntimeError(f'Job failed. Error message: {error}') + # `failure` is null unless the job failed, and absent after `cancel` or `delete`. + if failure := self._job.get('failure'): + raise RuntimeError(f"Job failed with {failure['code']}: {failure['message']}") if time_waited_seconds >= timeout_seconds: raise TimeoutError(f'Job timed out after waiting {time_waited_seconds} seconds.') raise RuntimeError( f'Job was not completed successfully. Instead had status: {self.status()}' ) + is_batch = self._job['type'] == 'ionq.multi-circuit.v1' backend_results = self._client.get_results( - job_id=self.job_id(), sharpen=sharpen, extra_query_params=extra_query_params + job_id=self.job_id(), + sharpen=sharpen, + extra_query_params=extra_query_params, + batch_mode=is_batch, ) - - # is this a batch run (dict-of-dicts) or a single circuit? - some_inner_value = next(iter(backend_results.values())) - is_batch = isinstance(some_inner_value, dict) histograms = list(backend_results.values()) if is_batch else [backend_results] # IonQ returns results in little endian, but diff --git a/cirq-ionq/cirq_ionq/job_test.py b/cirq-ionq/cirq_ionq/job_test.py index ae502f42f5..e4eb3540c6 100644 --- a/cirq-ionq/cirq_ionq/job_test.py +++ b/cirq-ionq/cirq_ionq/job_test.py @@ -15,7 +15,6 @@ from __future__ import annotations import json -import warnings from unittest import mock import pytest @@ -87,17 +86,16 @@ def test_job_results_qpu(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu', 'metadata': {'shots': 1000, 'measurement0': f'a{chr(31)}0,1'}, - 'warning': {'messages': ['foo', 'bar']}, } job = ionq.Job(mock_client, job_dict) - with warnings.catch_warnings(record=True) as w: - results = job.results() - assert len(w) == 2 - assert "foo" in str(w[0].message) - assert "bar" in str(w[1].message) + results = job.results() + mock_client.get_results.assert_called_once_with( + job_id='my_id', sharpen=None, extra_query_params=None, batch_mode=False + ) expected = ionq.QPUResult({0: 600, 1: 400}, 2, {'a': [0, 1]}) assert results == expected @@ -111,6 +109,7 @@ def test_batch_job_results_qpu(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.multi-circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu', 'metadata': { @@ -120,14 +119,12 @@ def test_batch_job_results_qpu(): ), 'qubit_numbers': json.dumps([2, 1]), }, - 'warning': {'messages': ['foo', 'bar']}, } job = ionq.Job(mock_client, job_dict) - with warnings.catch_warnings(record=True) as w: - results = job.results() - assert len(w) == 2 - assert "foo" in str(w[0].message) - assert "bar" in str(w[1].message) + results = job.results() + mock_client.get_results.assert_called_once_with( + job_id='my_id', sharpen=None, extra_query_params=None, batch_mode=True + ) expected_0 = ionq.QPUResult({0: 600, 1: 400}, 2, {'a': [0, 1]}) expected_1 = ionq.QPUResult({1: 1000}, 1, {'a': [0]}) assert results[0] == expected_0 @@ -140,6 +137,7 @@ def test_job_results_rounding_qpu(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu', 'metadata': {'shots': 5000, 'measurement0': f'a{chr(31)}0,1'}, @@ -152,15 +150,16 @@ def test_job_results_rounding_qpu(): def test_job_results_failed(): - job_dict = {'id': 'my_id', 'status': 'failed', 'failure': {'error': 'too many qubits'}} + failure = {'code': 'InvalidInput', 'message': 'too many qubits'} + job_dict = {'id': 'my_id', 'status': 'failed', 'failure': failure} job = ionq.Job(None, job_dict) - with pytest.raises(RuntimeError, match='too many qubits'): + with pytest.raises(RuntimeError, match='InvalidInput: too many qubits'): _ = job.results() assert job.status() == 'failed' def test_job_results_failed_no_error_message(): - job_dict = {'id': 'my_id', 'status': 'failed', 'failure': {}} + job_dict = {'id': 'my_id', 'status': 'failed', 'failure': None} job = ionq.Job(None, job_dict) with pytest.raises(RuntimeError, match='failed'): _ = job.results() @@ -173,6 +172,7 @@ def test_job_results_qpu_endianness(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu', 'metadata': {'shots': 1000}, @@ -190,6 +190,7 @@ def test_batch_job_results_qpu_endianness(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.multi-circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu', 'metadata': { @@ -209,6 +210,7 @@ def test_job_results_qpu_target_endianness(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu.target', 'metadata': {'shots': 1000}, @@ -227,6 +229,7 @@ def test_batch_job_results_qpu_target_endianness(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.multi-circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'qpu.target', 'metadata': { @@ -247,6 +250,7 @@ def test_job_results_poll(mock_sleep): completed_job = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'qpu', 'metadata': {'shots': 1000}, @@ -273,7 +277,8 @@ def test_job_results_poll_timeout(mock_sleep): @mock.patch('time.sleep', return_value=None) def test_job_results_poll_timeout_with_error_message(mock_sleep): - ready_job = {'id': 'my_id', 'status': 'failure', 'failure': {'error': 'too many qubits'}} + failure = {'code': 'InvalidInput', 'message': 'too many qubits'} + ready_job = {'id': 'my_id', 'status': 'failure', 'failure': failure} mock_client = mock.MagicMock() mock_client.get_job.return_value = ready_job job = ionq.Job(mock_client, ready_job) @@ -288,6 +293,7 @@ def test_job_results_simulator(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'simulator', 'metadata': {'shots': '100'}, @@ -306,6 +312,7 @@ def test_batch_job_results_simulator(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.multi-circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'simulator', 'metadata': { @@ -330,6 +337,7 @@ def test_job_results_simulator_endianness(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'simulator', 'metadata': {'shots': '100'}, @@ -347,6 +355,7 @@ def test_batch_job_results_simulator_endianness(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.multi-circuit.v1', 'stats': {'qubits': '2'}, 'backend': 'simulator', 'metadata': { @@ -366,6 +375,7 @@ def test_job_sharpen_results(): job_dict = { 'id': 'my_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'simulator', 'metadata': {'shots': '100'}, @@ -423,7 +433,7 @@ def test_job_fields_cannot_get_status(): 'backend': 'qpu', 'name': 'bacon', 'stats': {'qubits': '5'}, - 'status': 'running', + 'status': 'started', 'metadata': {'shots': 1000}, } mock_client = mock.MagicMock() @@ -445,7 +455,7 @@ def test_job_fields_update_status(): 'backend': 'qpu', 'name': 'bacon', 'stats': {'qubits': '5'}, - 'status': 'running', + 'status': 'started', 'metadata': {'shots': 1000}, } mock_client = mock.MagicMock() diff --git a/cirq-ionq/cirq_ionq/sampler.py b/cirq-ionq/cirq_ionq/sampler.py index 25db1bf65c..fff49c3879 100644 --- a/cirq-ionq/cirq_ionq/sampler.py +++ b/cirq-ionq/cirq_ionq/sampler.py @@ -56,8 +56,8 @@ def __init__( Args: service: The service used to create this sample. - target: Where to run the job. Can be 'qpu' or 'simulator'. If this is not specified, - there must be a default target set on `service`. + target: Where to run the job, for example 'simulator' or 'qpu.forte-1'. If this is + not specified, there must be a default target set on `service`. seed: If the target is `simulation` the seed for generating results. If None, this will be `np.random`, if an int, will be `np.random.RandomState(int)`, otherwise must be a modulate similar to `np.random`. diff --git a/cirq-ionq/cirq_ionq/sampler_test.py b/cirq-ionq/cirq_ionq/sampler_test.py index 7ebe99250b..1d46e2a819 100644 --- a/cirq-ionq/cirq_ionq/sampler_test.py +++ b/cirq-ionq/cirq_ionq/sampler_test.py @@ -28,6 +28,7 @@ def test_sampler_qpu(): job_dict = { 'id': '1', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'qpu', 'metadata': {'shots': 4, 'measurement0': f'a{chr(31)}0'}, @@ -52,6 +53,7 @@ def test_sampler_simulator(): job_dict = { 'id': '1', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'simulator', 'metadata': {'shots': 4, 'measurement0': f'a{chr(31)}0'}, @@ -78,6 +80,7 @@ def test_sampler_multiple_jobs(): job_dict0 = { 'id': '1', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'qpu', 'metadata': {'shots': 4, 'measurement0': f'a{chr(31)}0'}, @@ -85,6 +88,7 @@ def test_sampler_multiple_jobs(): job_dict1 = { 'id': '1', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'qpu', 'metadata': {'shots': 4, 'measurement0': f'a{chr(31)}0'}, @@ -128,6 +132,7 @@ def test_sampler_run_sweep(): job_dict = { 'id': '1', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'qpu', 'metadata': {'shots': 4, 'measurement0': f'a{chr(31)}0'}, diff --git a/cirq-ionq/cirq_ionq/service.py b/cirq-ionq/cirq_ionq/service.py index f5c5895d07..4b7e907f3e 100644 --- a/cirq-ionq/cirq_ionq/service.py +++ b/cirq-ionq/cirq_ionq/service.py @@ -54,8 +54,8 @@ def __init__( variable is not set, then this will raise an `EnvironmentError`. default_target: Which target to default to using. If set to None, no default is set and target must always be specified in calls. If set, then this default is used, - unless a target is specified for a given call. Supports either 'qpu' or - 'simulator'. + unless a target is specified for a given call. For example 'simulator' or + 'qpu.forte-1'. api_version: Version of the api. Defaults to 'v0.4'. max_retry_seconds: The number of seconds to retry calls for. Defaults to one hour. job_settings: A dictionary of settings which can override behavior for circuits when @@ -113,7 +113,7 @@ def run( circuit: The circuit to run. repetitions: The number of times to run the circuit. name: An optional name for the created job. Different from the `job_id`. - target: Where to run the job. Can be 'qpu' or 'simulator'. + target: Where to run the job, for example 'simulator' or 'qpu.forte-1'. param_resolver: A `cirq.ParamResolver` to resolve parameters in `circuit`. seed: If the target is `simulation` the seed for generating results. If None, this will be `np.random`, if an int, will be `np.random.RandomState(int)`, otherwise @@ -186,7 +186,7 @@ def run_batch( circuits: The circuits to run. repetitions: The number of times to run each circuits. name: An optional name for the created job. Different from the `job_id`. - target: Where to run the job. Can be 'qpu' or 'simulator'. + target: Where to run the job, for example 'simulator' or 'qpu.forte-1'. param_resolver: A `cirq.ParamResolver` to resolve parameters in `circuit`. seed: If the target is `simulation` the seed for generating results. If None, this will be `np.random`, if an int, will be `np.random.RandomState(int)`, otherwise @@ -282,7 +282,7 @@ def create_job( circuit: The circuit to run. repetitions: The number of times to repeat the circuit. Defaults to 100. name: An optional name for the created job. Different from the `job_id`. - target: Where to run the job. Can be 'qpu' or 'simulator'. + target: Where to run the job, for example 'simulator' or 'qpu.forte-1'. compilation (dict): settings for compilation when creating a job, default values: {"opt": 0, "precision": "1E-3"} error_mitigation (dict): settings for error mitigation when creating a job. @@ -350,7 +350,7 @@ def create_batch_job( circuits: The circuits to run. repetitions: The number of times to repeat the circuit. Defaults to 100. name: An optional name for the created job. Different from the `job_id`. - target: Where to run the job. Can be 'qpu' or 'simulator'. + target: Where to run the job, for example 'simulator' or 'qpu.forte-1'. compilation (dict): settings for compilation when creating a job, default values: {"opt": 0, "precision": "1E-3"} error_mitigation (dict): settings for error mitigation when creating a job. @@ -418,14 +418,14 @@ def get_job(self, job_id: str) -> job.Job: return job.Job(client=self._client, job_dict=job_dict) 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 ) -> Sequence[job.Job]: """Lists jobs that have been created on the IonQ API. Args: status: If supplied will filter to only 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 sequence of jobs. @@ -436,22 +436,23 @@ def list_jobs( job_dicts = self._client.list_jobs(status=status, limit=limit, batch_size=batch_size) return tuple(job.Job(client=self._client, job_dict=job_dict) for job_dict in job_dicts) - def get_current_calibration(self) -> calibration.Calibration: - """Gets the most recent calibration via the API. - - Note that currently there is only one target, so this returns the calibration of that - target. + def get_current_calibration(self, target: str | None = None) -> calibration.Calibration: + """Gets the most recent calibration of a QPU via the API. The calibration include device specification (number of qubits, connectivity), as well as fidelities and timings of gates. + Args: + target: The QPU to get the calibration of. If not set, uses `default_target`. + Returns: A `cirq_ionq.Calibration` containing the device specification and calibrations. Raises: + IonQNotFoundException: If the target has no calibrations, as for the simulator. IonQException: If there was an error accessing the API. """ - calibration_dict = self._client.get_current_calibration() + calibration_dict = self._client.get_current_calibration(target=target) return calibration.Calibration(calibration_dict=calibration_dict) def list_calibrations( @@ -459,15 +460,16 @@ def list_calibrations( start: datetime.datetime | None = None, end: datetime.datetime | None = None, limit: int = 100, - batch_size: int = 1000, + *, + target: str | None = None, ) -> Sequence[calibration.Calibration]: - """List calibrations via the API. + """List calibrations of a QPU via the 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 sequence of calibrations. @@ -476,6 +478,6 @@ def list_calibrations( IonQException: If there was an error accessing the API. """ calibration_dicts = self._client.list_calibrations( - start=start, end=end, limit=limit, batch_size=batch_size + start=start, end=end, limit=limit, target=target ) return [calibration.Calibration(calibration_dict=c) for c in calibration_dicts] diff --git a/cirq-ionq/cirq_ionq/service_test.py b/cirq-ionq/cirq_ionq/service_test.py index e9c90767d2..4a9f563d3c 100644 --- a/cirq-ionq/cirq_ionq/service_test.py +++ b/cirq-ionq/cirq_ionq/service_test.py @@ -38,6 +38,7 @@ def test_service_run(target, expected_results): mock_client.get_job.return_value = { 'id': 'job_id', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'backend': target, 'metadata': {'shots': '4', 'measurement0': f'a{chr(31)}0'}, 'stats': {'qubits': '1'}, @@ -77,6 +78,7 @@ def test_service_run_batch(target, expected_results1, expected_results2): mock_client.get_job.return_value = { 'id': 'job_id', 'status': 'completed', + 'type': 'ionq.multi-circuit.v1', 'backend': target, 'metadata': { 'shots': '4', @@ -132,6 +134,7 @@ def test_sampler(): job_dict = { 'id': '1', 'status': 'completed', + 'type': 'ionq.circuit.v1', 'stats': {'qubits': '1'}, 'backend': 'qpu', 'metadata': {'shots': 4, 'measurement0': f'a{chr(31)}0'}, @@ -201,9 +204,9 @@ def test_service_get_current_calibration(): mock_client.get_current_calibration.return_value = calibration_dict service._client = mock_client - cal = service.get_current_calibration() + cal = service.get_current_calibration(target='qpu.forte-1') assert cal.num_qubits() == 11 - mock_client.get_current_calibration.assert_called_once() + mock_client.get_current_calibration.assert_called_once_with(target='qpu.forte-1') def test_service_list_calibrations(): @@ -215,10 +218,14 @@ def test_service_list_calibrations(): start = datetime.datetime.fromtimestamp(1284286794, datetime.UTC) end = datetime.datetime.fromtimestamp(1284286795, datetime.UTC) - listed_calibrations = service.list_calibrations(start=start, end=end, limit=10, batch_size=2) + listed_calibrations = service.list_calibrations( + start=start, end=end, limit=10, target='qpu.forte-1' + ) assert listed_calibrations[0].num_qubits() == 1 assert listed_calibrations[1].num_qubits() == 2 - mock_client.list_calibrations.assert_called_with(start=start, end=end, limit=10, batch_size=2) + mock_client.list_calibrations.assert_called_with( + start=start, end=end, limit=10, target='qpu.forte-1' + ) @mock.patch.dict(os.environ, {'IONQ_API_KEY': 'tomyheart'}) @@ -348,6 +355,7 @@ def test_run_batch_preserves_order(target): client.get_job.return_value = { "id": "job_id", "status": "completed", + "type": "ionq.multi-circuit.v1", "backend": target, "qubits": "1", "metadata": { diff --git a/docs/hardware/ionq/calibrations.md b/docs/hardware/ionq/calibrations.md index c5e1e41bd4..b296e41f79 100644 --- a/docs/hardware/ionq/calibrations.md +++ b/docs/hardware/ionq/calibrations.md @@ -28,7 +28,7 @@ See [IonQ API Service](service.md) for how to set up the service. To get the latest calibration, you simply query the service for the calibration object ```python -calibration = service.get_current_calibration() +calibration = service.get_current_calibration(target='qpu.forte-1') ``` The returned object then has data about the target (currently only on QPU) as well as the current performance of the target. @@ -36,7 +36,7 @@ as well as the current performance of the target. ```python print(calibration.fidelities()) # prints something like -{'1q': {'mean': 0.99717}, '2q': {'mean': 0.9696}, 'spam': {'mean': 0.9961}} +{'spam': {'median': 0.995}, '1q': {'median': 0.9998, 'stderr': 0.0001}, '2q': {'median': 0.99, 'stderr': 0.001}} ``` Here * `1q` and `2q` refer to one and two qubit average gate fidelities measured using @@ -66,4 +66,4 @@ These measurements are all returned in seconds A few other properties of the `ionq.Calibration` object are * `num_qubits`: the number of qubits on the QPU. * `connectivity`: a set of all the possible qubits that can interact in the set. -* `target`: in the future when there are multiple QPUs this will list which target. +* `target`: the name of the QPU, for example `qpu.forte-1`. diff --git a/docs/hardware/ionq/circuits.md b/docs/hardware/ionq/circuits.md index 05b0b3c929..a2e62e7c3f 100644 --- a/docs/hardware/ionq/circuits.md +++ b/docs/hardware/ionq/circuits.md @@ -35,7 +35,7 @@ of qubits on the device minus one, inclusively. To get the number of qubits on the device, you can query the calibration: ```python -calibration = service.get_current_calibration() +calibration = service.get_current_calibration(target='qpu.forte-1') num_qubits = calibration.num_qubits() print(num_qubits) ``` diff --git a/docs/hardware/ionq/getting_started.ipynb b/docs/hardware/ionq/getting_started.ipynb index 14cfaa3f51..48dc90aeee 100644 --- a/docs/hardware/ionq/getting_started.ipynb +++ b/docs/hardware/ionq/getting_started.ipynb @@ -123,7 +123,7 @@ "id": "042b4395ec4e" }, "source": [ - "Note that we have set the `default_target` to `simulator`. The other option would be to set it to `qpu`.\n", + "Note that we have set the `default_target` to `simulator`. The other option would be to set it to a QPU, such as `qpu.forte-1`.\n", "\n", "## Running a simple circuit\n", "\n", @@ -181,7 +181,7 @@ } ], "source": [ - "result = service.run(circuit, repetitions=100, target='qpu')\n", + "result = service.run(circuit, repetitions=100, target='qpu.forte-1')\n", "print(result)" ] }, diff --git a/docs/hardware/ionq/jobs.md b/docs/hardware/ionq/jobs.md index 84484706b4..5a711e2571 100644 --- a/docs/hardware/ionq/jobs.md +++ b/docs/hardware/ionq/jobs.md @@ -27,7 +27,7 @@ then this job is held in a queue before being scheduled to run on the appropriat hardware (QPU) or simulator. Once a job is created (but not necessarily yet run) on the scheduler, the job is assigned an id and then you can query this job via the API. The job has a status on it, which describes what state the job is in -`running`, `completed`, `failed`, etc. From a users perspective, this is abstracted +`started`, `completed`, `failed`, etc. From a users perspective, this is abstracted mostly away in Cirq. A job can be run in either block modes, or non-blocking mode, as described below. @@ -44,7 +44,7 @@ circuit = cirq.Circuit( cirq.measure(qubit, key='x'), # Measurement store in key 'x' ) -result = service.run(circuit=circuit, repetitions=100, target='qpu') +result = service.run(circuit=circuit, repetitions=100, target='qpu.forte-1') print(result) ``` @@ -66,8 +66,8 @@ in an order corresponding to the temporal order of the measurements. When calling run, you will need to include the number of `repetitions` or shots for the given circuit. In addition, if there is no `default_target` set on the -service, then a `target` needs to be specified. Currently the supported targets -are `qpu` and `simulator`. +service, then a `target` needs to be specified. The supported targets are +`simulator` and the QPUs, for example `qpu.forte-1`. ### Via a sampler @@ -89,7 +89,7 @@ circuit = cirq.Circuit( cirq.X(qubit)**0.5, # Square root of NOT. cirq.measure(qubit, key='x') # Measurement store in key 'x' ) -sampler = service.sampler(target='qpu') +sampler = service.sampler(target='qpu.forte-1') result = sampler.run(program=circuit, repetitions=100) print(result) ``` @@ -116,7 +116,7 @@ circuit = cirq.Circuit( cirq.X(qubit)**0.5, # Square root of NOT. cirq.measure(qubit, key='x') # Measurement store in key 'x' ) -job = service.create_job(circuit=circuit, target='qpu', repetitions=100) +job = service.create_job(circuit=circuit, target='qpu.forte-1', repetitions=100) print(job) ``` diff --git a/docs/hardware/ionq/service.md b/docs/hardware/ionq/service.md index 98ee068c6b..9163d58c96 100644 --- a/docs/hardware/ionq/service.md +++ b/docs/hardware/ionq/service.md @@ -46,7 +46,7 @@ service = ionq.Service(api_key=API_KEY) # Run a program against the service. This method will block execution until # the result is returned (determined by periodically polling the IonQ API). -result = service.run(circuit=circuit, repetitions=100, target='qpu') +result = service.run(circuit=circuit, repetitions=100, target='qpu.forte-1') # The return object of run is a cirq.Result object. # From this object, you can get a histogram of results. @@ -87,7 +87,7 @@ when creating a `cirq_ionq.Service` object. * `remote_host`: The location of the API in the form of a URL. If this is None, then this instance will use the environment variable `IONQ_REMOTE_HOST`. If that variable is not set, then this uses `https://api.ionq.co/{api_version}`. -* `default_target`: this is a string of either `simulator` or `qpu`. By setting this, you do not have to specify a target every time you run a job using `run`, `create_job` or via the `sampler` interface. A helpful pattern is to create two services with defaults for the simulator and for the QPU separately. +* `default_target`: this is a string naming a target, such as `simulator` or `qpu.forte-1`. By setting this, you do not have to specify a target every time you run a job using `run`, `create_job` or via the `sampler` interface. A helpful pattern is to create two services with defaults for the simulator and for the QPU separately. * `api_version`: Version of the API to be used. Defaults to 'v0.4'. * `max_retry_seconds`: The API will poll with exponential backoff for completed jobs. By specifying this, you can change the number of seconds before this retry gives up. It is common to set this to a very small number when, for example, wanting to fail fast, or to be set very high for long running jobs. @@ -98,11 +98,11 @@ When running a job, there are several parameters that can be provided: * `circuit`: The `cirq.Circuit` to run. * `repetitions`: The number of times to run the circuit. * `name`: An name for the created job (optional.) -* `target`: Where to run the job. Can be 'qpu' or 'simulator'. +* `target`: Where to run the job, for example 'simulator' or 'qpu.forte-1'. * `param_resolver`: A `cirq.ParamResolver` to resolve parameters in `circuit`. * `seed`: For `simulation` jobs, specify the seed for simulating results. If None, this will be `np.random`, if an int, will be `np.random.RandomState(int)`, otherwise must be a modulate similar to `np.random`. * `error_mitigation`: A dictionary of error mitigation settings. Valid keys include: - - 'debias': Set to true to turn on [debiasing](https://ionq.com/resources/debiasing-and-sharpening), which can improve circuit performance by removing qubit-specific noise. _Debiasing is on by default for Aria-class systems._ + - 'debiasing': Set to true to turn on [debiasing](https://ionq.com/resources/debiasing-and-sharpening), which can improve circuit performance by removing qubit-specific noise. _Debiasing is on by default for Aria-class systems._ * `sharpen`: Get sharpened results from debiasing. Off by default. Will generally return more accurate results if your expected output distribution has peaks. * `extra_query_params`: A dictionary that specifies additional parameters to be provided in the request. (Currently unused) @@ -113,8 +113,8 @@ Here is an example of using error mitigation and sharpening options: result = service.run( circuit=circuit, repetitions=100, - target='qpu', - error_mitigation={'debias': True}, + target='qpu.forte-1', + error_mitigation={'debiasing': True}, sharpen=True, ) ```