API documentation

Contents

API documentation#

The pytket-quantinuum extension allows submission of pytket circuits to the H-series trapped ion devices (and emulators) via the QuantinuumBackend.

Consult the notebooks for some example usage.

enum pytket.extensions.quantinuum.Language(value)[source]#

Language used for submission of circuits.

Valid values are as follows:

QASM = <Language.QASM: 'OPENQASM 2.0'>#
QIR = <Language.QIR: 'QIR 1.0'>#
class pytket.extensions.quantinuum.QuantinuumBackend(device_name, label='job', simulator='state-vector', group=None, provider=None, machine_debug=False, api_handler=<pytket.extensions.quantinuum.backends.api_wrappers.QuantinuumAPI object>, compilation_config=None, **kwargs)[source]#

Bases: Backend

Interface to a Quantinuum device. More information about the QuantinuumBackend can be found on this page https://tket.quantinuum.com/extensions/pytket-quantinuum/index.html

__init__(device_name, label='job', simulator='state-vector', group=None, provider=None, machine_debug=False, api_handler=<pytket.extensions.quantinuum.backends.api_wrappers.QuantinuumAPI object>, compilation_config=None, **kwargs)[source]#

Construct a new Quantinuum backend.

Parameters:
  • device_name (str) – Name of device, e.g. “H1-1”

  • label (Optional[str]) – Job labels used if Circuits have no name, defaults to “job”

  • simulator (str) – Only applies to simulator devices, options are “state-vector” or “stabilizer”, defaults to “state-vector”

  • group (Optional[str]) – string identifier of a collection of jobs, can be used for usage tracking.

  • provider (Optional[str]) – select a provider for federated authentication. We currently only support ‘microsoft’, which enables the microsoft Device Flow.

  • api_handler (QuantinuumAPI) – Instance of API handler, defaults to DEFAULT_API_HANDLER

  • compilation_config (Optional[QuantinuumBackendCompilationConfig]) – Optional compilation configuration

Supported kwargs:

add_to_batch(batch_start_job, circuit, n_shots=None, batch_end=False, valid_check=True, **kwargs)[source]#

Add to a batch of jobs on the backend, behaves like process_circuit except in two ways:

1. The first argument must be the result handle of the first job of batch.

2. The optional argument batch_end should be set to “True” for the final circuit of the batch. By default it is False.

See pytket.backends.Backend.process_circuits() for documentation on remaining parameters.

Parameters:
  • batch_start_job (ResultHandle) – Handle of first circuit submitted to batch.

  • batch_end (bool) – Boolean flag to signal the final circuit of batch, defaults to False

Return type:

ResultHandle

Returns:

Handle for submitted circuit.

classmethod available_devices(**kwargs)[source]#

See pytket.backends.Backend.available_devices().

Parameters:

api_handler – Instance of API handler, defaults to DEFAULT_API_HANDLER

Return type:

List[BackendInfo]

Returns:

A list of BackendInfo objects for each available Backend.

cancel(handle)[source]#

Cancel a job.

Parameters:

handle (ResultHandle) – handle to job

Raises:

NotImplementedError – If backend does not support job cancellation

Return type:

None

circuit_status(handle, **kwargs)[source]#

Return a CircuitStatus reporting the status of the circuit execution corresponding to the ResultHandle

Return type:

CircuitStatus

cost(circuit, n_shots, syntax_checker=None, use_websocket=None, **kwargs)[source]#

Return the cost in HQC to process this circuit with n_shots repeats on this backend.

The cost is obtained by sending the circuit to a “syntax-checker” backend, which incurs no cost itself but reports what the cost would be for the actual backend (self).

If self is a syntax checker then the cost will be zero.

See QuantinuumBackend.process_circuits() for the supported kwargs.

Parameters:
  • circuit (Circuit) – Circuit to calculate runtime estimate for. Must be valid for backend.

  • n_shots (int) – Number of shots.

  • syntax_checker (Optional[str]) – Optional. Name of the syntax checker to use to get cost. For example for the “H1-1” device that would be “H1-1SC”. For most devices this is automatically inferred, default=None.

  • use_websocket (Optional[bool]) – Optional. Boolean flag to use a websocket connection.

Raises:

ValueError – Circuit is not valid, needs to be compiled.

Return type:

Optional[float]

Returns:

Cost in HQC to execute the shots.

cost_estimate(circuit, n_shots)[source]#

Deprecated, use cost.

Return type:

Optional[float]

default_compilation_pass(optimisation_level=2)[source]#
Parameters:

optimisation_level (int) – Allows values of 0,1 or 2, with higher values prompting more computationally heavy optimising compilation that can lead to reduced gate count in circuits.

Return type:

BasePass

Returns:

Compilation pass for compiling circuits to Quantinuum devices

classmethod device_state(device_name, api_handler=<pytket.extensions.quantinuum.backends.api_wrappers.QuantinuumAPI object>)[source]#

Check the status of a device.

>>> QuantinuumBackend.device_state('H1') # e.g. "online"
Parameters:
  • device_name (str) – Name of the device.

  • api_handler (QuantinuumAPI) – Instance of API handler, defaults to DEFAULT_API_HANDLER

Return type:

str

Returns:

String of state, e.g. “online”

get_calendar(start_date, end_date, localise=True)[source]#

Retrieves the Quantinuum H-Series operations calendar for the period specified by start_date and end_date. The calendar data returned is for the local timezone of the end-user.

The output is a sorted list of dictionaries. Each dictionary is an event on the operations calendar for the period specified by the end-user. The output from this function can be readily used to instantiate a pandas.DataFrame.

The dictionary has the following properties. * ‘start-date’: The start date and start time as a datetime.datetime object. * ‘end-date’: The end date and end time as a datetime.datetime object. * ‘machine’: A string specifying the H-Series device attached to the event. * ‘event-type’: The type of event as a string. The value online denotes queued

access to the device, and the value reservation denotes priority access for a particular organisation.

  • ‘organization’: If the ‘event-type’ is assigned the value ‘reservation’, the

    organization with reservation access is specified. Only users within an organization have visibility on organization reservations. Otherwise, organization is listed as ‘Fair-Share Queue’, which means all users from all organizations are able to submit jobs to the Fairshare queue during this period.

Parameters:
  • start_date (datetime) – The start date as datetime.date object for the period to return the operations calendar.

  • end_date (datetime) – The end date as datetime.date object for the period to return the operations calendar.

  • localise (bool) – Apply localization to the datetime based on the end-users time zone. Default is True. Disable by setting False.

Return type:

List[Dict[str, Any]]

Returns:

A list of events from the H-Series operations calendar, sorted by the start-date of each event. Each event is a python dictionary.

Return_type:

List[Dict[str, str]]

Raises:

RuntimeError if an emulator or syntax-checker is specified

Raises:

ValueError if the argument start_date or end_date are not datetime.datetime objects.

get_compilation_config()[source]#

Get the current compilation configuration.

Return type:

QuantinuumBackendCompilationConfig

static get_jobid(handle)[source]#

Return the corresponding Quantinuum Job ID from a ResultHandle.

Parameters:

handle (ResultHandle) – result handle.

Return type:

str

Returns:

Quantinuum API Job ID string.

get_partial_result(handle)[source]#

Retrieve partial results for a given job, regardless of its current state.

Parameters:

handle (ResultHandle) – handle to results

Return type:

Tuple[Optional[BackendResult], CircuitStatus]

Returns:

A tuple containing the results and circuit status. If no results are available, the first element is None.

static get_ppcirc_rep(handle)[source]#

Return the JSON serialization of the classiocal postprocessing circuit attached to a handle, if any.

Parameters:

handle (ResultHandle) – result handle

Return type:

Any

Returns:

serialized post-processing circuit, if any

get_result(handle, **kwargs)[source]#

See pytket.backends.Backend.get_result(). Supported kwargs: timeout, wait, use_websocket.

Return type:

BackendResult

static get_results_selection(handle)[source]#

Return a list of pairs (register name, register index) representing the order of the expected results in the response. If None, then all results in the response are used, in lexicographic order.

Return type:

Any

static get_results_width(handle)[source]#

Return the truncation width of the results, if any.

Parameters:

handle (ResultHandle) – result handle

Return type:

Optional[int]

Returns:

truncation width of results, if any

login()[source]#

Log in to Quantinuum API. Requests username and password from stdin (e.g. shell input or dialogue box in Jupytet notebooks.). Passwords are not stored. After log in you should not need to provide credentials again while that session (script/notebook) is alive.

Return type:

None

logout()[source]#

Clear stored JWT tokens from login. Will need to login again to make API calls.

Return type:

None

process_circuits(circuits, n_shots=None, valid_check=True, **kwargs)[source]#

See pytket.backends.Backend.process_circuits().

Return type:

List[ResultHandle]

Supported kwargs#

  • postprocess: apply end-of-circuit simplifications and classical postprocessing to improve fidelity of results (bool, default False)

  • simplify_initial: apply the pytket SimplifyInitial pass to improve fidelity of results assuming all qubits initialized to zero (bool, default False)

  • noisy_simulation: boolean flag to specify whether the simulator should perform noisy simulation with an error model (default value is True).

  • group: string identifier of a collection of jobs, can be used for usage tracking. Overrides the instance variable group.

  • wasm_file_handler: a WasmFileHandler object for linked WASM module.

  • pytketpass: a pytket.passes.BasePass intended to be applied

    by the backend (beta feature, may be ignored).

  • options: items to add to the “options” dictionary of the request body, as a json-style dictionary (in addition to any that were set in the backend constructor)

  • request_options: extra options to add to the request body as a json-style dictionary

  • language: languange for submission, of type Language, default QASM.

  • leakage_detection: if true, adds additional Qubit and Bit to Circuit to detect leakage errors. Run prune_shots_detected_as_leaky on returned BackendResult to get counts with leakage errors removed.

  • seed: for local emulators only, PRNG seed for reproduciblity (int)

  • multithreading: for local emulators only, boolean to indicate whether to use multithreading for emulation (defaults to False)

rebase_pass()[source]#

A single compilation pass that when run converts all gates in a Circuit to an OpType supported by the Backend (ignoring architecture constraints).

Returns:

Compilation pass that converts gates to primitives supported by Backend.

Return type:

BasePass

set_compilation_config_allow_implicit_swaps(allow_implicit_swaps)[source]#

Set the option to allow or disallow implicit swaps during compilation.

Return type:

None

set_compilation_config_target_2qb_gate(target_2qb_gate)[source]#

Set the target two-qubit gate for compilation.

Return type:

None

start_batch(max_batch_cost, circuit, n_shots=None, valid_check=True, **kwargs)[source]#
Start a batch of jobs on the backend, behaves like process_circuit

but with additional parameter max_batch_cost as the first argument. See pytket.backends.Backend.process_circuits() for documentation on remaining parameters.

Parameters:

max_batch_cost (int) – Maximum cost to be used for the batch, if a job exceeds the batch max it will be rejected.

Return type:

ResultHandle

Returns:

Handle for submitted circuit.

submit_program(language, program, n_shots, name=None, noisy_simulation=True, group=None, wasm_file_handler=None, pytket_pass=None, options=None, request_options=None, results_selection=None)[source]#

Submit a program directly to the backend.

Parameters:
  • program (str) – program (encoded as string)

  • language (Language) – language

  • n_shots (int) – Number of shots

  • name (Optional[str]) – Job name, defaults to None

  • noisy_simulation (bool) – Boolean flag to specify whether the simulator should perform noisy simulation with an error model defaults to True

  • group (Optional[str]) – String identifier of a collection of jobs, can be used for usage tracking. Overrides the instance variable group, defaults to None

  • wasm_file_handler (Optional[WasmFileHandler]) – WasmFileHandler object for linked WASM module, defaults to None

  • pytket_pass (Optional[BasePass]) – pytket.passes.BasePass intended to be applied by the backend (beta feature, may be ignored), defaults to None

  • options (Optional[Dict[str, Any]]) – Items to add to the “options” dictionary of the request body

  • request_options (Optional[Dict[str, Any]]) – Extra options to add to the request body as a json-style dictionary, defaults to None

  • results_selection (Optional[List[Tuple[str, int]]]) – Ordered list of register names and indices used to construct final BackendResult. If None, all all results are used in lexicographic order.

Raises:
  • WasmUnsupported – WASM submitted to backend that does not support it.

  • QuantinuumAPIError – API error.

  • ConnectionError – Connection to remote API failed

Return type:

ResultHandle

Returns:

ResultHandle for submitted job.

view_calendar(month, year, figsize=(40, 20), fontsize=15, titlesize=40)[source]#

Visualise the H-Series operations calendar for a user-specified month and year. The operations hours are shown for the machine name used to construct the QuantinuumBackend object, i.e. ‘H1-1’. Operations days are coloured. In addition, a description of the event is also displayed (start-time, duration and event-type, see the get_calendar method for more information).

Parameters:
  • month (int) – An integer specifying the calendar month to visualise. 1 is January and 12 is December.

  • year (int) – An integer specifying the calendar year to visualise.

  • figsize (Tuple[float, float]) – A tuple specifying width and height of the output matplotlib.figure.Figure.

  • fontsize (float) – The fontsize of the event description within the calendar.

Return type:

matplotlib.figure.Figure

Returns:

A matplotlib.figure.Figure visualising the H-Series calendar for a user-specified calendar month.

Return_type:

matplotlib.figure.Figure

property backend_info: BackendInfo | None#

Retrieve all Backend properties in a BackendInfo object, including device architecture, supported gate set, gate errors and other hardware-specific information.

Returns:

The BackendInfo describing this backend if it exists.

Return type:

Optional[BackendInfo]

property default_two_qubit_gate: OpType#

Returns the default two-qubit gate for the device.

property is_local_emulator: bool#

True if the backend is a local emulator, otherwise False

property required_predicates: List[Predicate]#

The minimum set of predicates that a circuit must satisfy before it can be successfully run on this backend.

Returns:

Required predicates.

Return type:

List[Predicate]

property two_qubit_gate_set: Set[OpType]#

Returns the set of supported two-qubit gates.

Submitted circuits must contain only one of these.

class pytket.extensions.quantinuum.QuantinuumBackendCompilationConfig(allow_implicit_swaps=True, target_2qb_gate=None)[source]#

Options to configure default compilation and rebase passes.

  • allow_implicit_swaps: Whether to allow use of implicit swaps when rebasing. The default is to allow implicit swaps.

  • target_2qb_gate: Choice of two-qubit gate. The default is to use the device’s default.

class pytket.extensions.quantinuum.QuantinuumAPI(token_store=None, api_url=None, api_version=1, use_websocket=True, provider=None, support_mfa=True, session=None, _QuantinuumAPI__user_name=None, _QuantinuumAPI__pwd=None)[source]#

Interface to the Quantinuum online remote API.

cancel(job_id)[source]#

Cancels job.

Parameters:

job_id (str) – job ID to cancel

Return type:

dict

Returns:

(dict) output from API

delete_authentication()[source]#

Remove stored credentials and tokens

Return type:

None

full_login()[source]#

Ask for user credentials from std input and update JWT tokens

Return type:

None

get_calendar(start_date, end_date)[source]#

Retrieves calendar data using L4 API. All dates and times are in the UTC timezone.

Parameters:
  • start_date (str) – String formatted start date (YYYY-MM-DD)

  • end_date (str) – String formatted end date (YYYY-MM-DD)

Return type:

List[Dict[str, str]]

Returns:

(dict) output from API

login()[source]#

This methods checks if we have a valid (non-expired) id-token and returns it, otherwise it gets a new one with refresh-token. If refresh-token doesn’t exist, it asks user for credentials.

Return type:

str

Returns:

(str) login token

retrieve_job(job_id, use_websocket=None)[source]#

Retrieves job from device.

Parameters:
  • job_id (str) – unique id of job

  • use_websocket (Optional[bool]) – use websocket to minimize interaction

Return type:

Optional[Dict]

Returns:

(dict) output from API

retrieve_job_status(job_id, use_websocket=None)[source]#

Retrieves job status from device.

Parameters:
  • job_id (str) – unique id of job

  • use_websocket (Optional[bool]) – use websocket to minimize interaction

Return type:

Optional[Dict]

Returns:

(dict) output from API

status(machine)[source]#

Check status of machine.

Parameters:

machine (str) – machine name

Return type:

str

Returns:

(str) status of machine

class pytket.extensions.quantinuum.QuantinuumAPIOffline(machine_list=None)[source]#

Offline copy of the interface to the Quantinuum remote API.

cancel(job_id)[source]#

No cancel offline

Return type:

dict

full_login()[source]#

No login offline with the offline API

Return type:

None

get_jobs()[source]#

The function will return all the jobs that have been submitted

Return type:

Optional[list]

Returns:

List of all the submitted jobs

login()[source]#

No login offline with the offline API, this function will always return an empty api token

Return type:

str

retrieve_job(job_id, use_websocket=None)[source]#

No retrieve_job_status offline

Return type:

None

retrieve_job_status(job_id, use_websocket=None)[source]#

No retrieve_job_status offline

Return type:

None

status(machine)[source]#

No retrieve_job_status offline

Return type:

str

Quantinuum config.

class pytket.extensions.quantinuum.backends.config.QuantinuumConfig(username, refresh_token, id_token, refresh_token_timeout, id_token_timeout)[source]#

Holds config parameters for pytket-quantinuum.

classmethod from_extension_dict(ext_dict)[source]#

Abstract method to build PytketExtConfig from dictionary serialized form.

Return type:

QuantinuumConfig

pytket.extensions.quantinuum.backends.config.set_quantinuum_config(username)[source]#

Set default value for Quantinuum username. Can be overriden in backend construction.

Return type:

None

Methods for generating a leakage detection Pytket Circuit.

pytket.extensions.quantinuum.backends.leakage_gadget.get_detection_circuit(circuit, n_device_qubits)[source]#

For a passed circuit, appends a leakage detection circuit for each end of circuit measurement using spare device qubits. All additional Qubit added for leakage detection are written to a new register “leakage_detection_qubit” and all additional Bit are written to a new register “leakage_detection_bit”.

Parameters:
  • circuit (Circuit) – Circuit to have leakage detection added.

  • n_device_qubits (int) – Total number of qubits supported by the device being compiled to.

Return type:

Circuit

Returns:

Circuit with leakage detection circuitry added.

pytket.extensions.quantinuum.backends.leakage_gadget.get_leakage_gadget_circuit(circuit_qubit, postselection_qubit, postselection_bit)[source]#

Returns a two qubit Circuit for detecting leakage errors.

Parameters:
  • circuit_qubit (Qubit) – Generated circuit detects whether leakage errors have occurred in this qubit.

  • postselection_qubit (Qubit) – Measured qubit to detect leakage error.

  • postselection_bit (Bit) – Leakage detection result is written to this bit.

Return type:

Circuit

Returns:

Circuit for detecting leakage errors for specified ids.

pytket.extensions.quantinuum.backends.leakage_gadget.prune_shots_detected_as_leaky(result)[source]#

For all states with a Bit with name “leakage_detection_bit” in a state 1 sets the counts to 0.

Parameters:

result (BackendResult) – Shots returned from device.

Returns:

Shots with leakage cases removed.

Return type:

BackendResult

class pytket.extensions.quantinuum.backends.credential_storage.MemoryCredentialStorage(id_token_timedelt=datetime.timedelta(seconds=3300), refresh_token_timedelt=datetime.timedelta(days=29))[source]#

In memory credential storage. Intended use is only to store id tokens, refresh tokens and user_name. Password storage is only included for debug purposes.

delete_credential()[source]#

delete credential

Return type:

None

save_id_token(id_token)[source]#

save ID token

Return type:

None

save_refresh_token(refresh_token)[source]#

save refresh token

Return type:

None

save_user_name(user_name)[source]#

save user_name

Return type:

None

property id_token: str | None#

returns a ID token if valid

property refresh_token: str | None#

returns a refresh token if valid

property user_name: str | None#

returns the user name

class pytket.extensions.quantinuum.backends.credential_storage.QuantinuumConfigCredentialStorage(id_token_timedelt=datetime.timedelta(seconds=3300), refresh_token_timedelt=datetime.timedelta(days=29))[source]#

Store tokens in the default pytket configuration file.

delete_credential()[source]#

delete credential

Return type:

None

save_id_token(id_token)[source]#

save ID token

Return type:

None

save_refresh_token(refresh_token)[source]#

save refresh token

Return type:

None

save_user_name(user_name)[source]#

save user_name

Return type:

None

property id_token: str | None#

returns a ID token if valid

property refresh_token: str | None#

returns a refresh token if valid

property user_name: str | None#

returns the user name