inquanto.protocols

Protocols for Expectation Values

class PauliAveraging(backend=None, shots_per_circuit=8000, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_colour_method=GraphColourMethod.Lazy)

Bases: ProtocolListItem, PartiallyPickleable, QermitRunMixin, ComputableCompliantMixin

Calculates the expectation value of a Hermitian operator by operator averaging the system register.

Implements the ‘Operator Averaging’ procedure (see: arXiv:1407.7863, arXiv:1510.04279).

Parameters:
  • backend (Optional[Backend], default: None) – The backend to use for quantum computations.

  • shots_per_circuit (int, default: 8000) – Number of shots for each circuit. Default is 8000.

  • pauli_partition_strategy (Optional[PauliPartitionStrat], default: PauliPartitionStrat.NonConflictingSets) – Strategy to partition Pauli operators.

  • pauli_colour_method (Optional[GraphColourMethod], default: GraphColourMethod.Lazy) – Method to perform graph colouring.

build(parameters, state, *operators, noise_mitigation=None, optimisation_level=1)

Builds the necessary circuits and measurement data for the state and Pauli strings in the operators.

Note

The coefficients in the operators are ignored.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – A dictionary or SymbolDict containing the parameter values for the circuits.

  • state (GeneralAnsatz) – Parametrized input state.

  • operators (QubitOperator) – Qubit operators, the Pauli strings in these QubitOperator objects are used to generate measurement circuits.

  • noise_mitigation (Optional[NoiseMitigation], default: None) – The noise mitigation instance containing pre and post mitigation strategies.

  • optimisation_level (int, default: 1) – Passed to the backend’s get_compiled_circuits() method.

Returns:

PauliAveraging – Self instance.

build_from(parameters, computable, exclude=None, noise_mitigation=None)

Build the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and collects all qubit operators appearing in nodes of type:

After it has walked over the tree, it calls the build method.

Raises:

NotImplementedError – If not all ExpectationValue nodes in the computable tree contain the same state.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameters for building.

  • computable (ComputableNode) – A root node of a computable expression tree, simply it is a computable expression.

  • exclude (Optional[Callable[[ComputableNode], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

  • noise_mitigation (Optional[NoiseMitigation], default: None) – The noise mitigation instance containing pre and post mitigation strategies.

Returns:

PauliAveraging – Modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, noise_mitigation=None, *args, **kwargs)

Build a list of protocols based on the given parameters and computable expression.

This method walks over the computable expression tree and collects all qubit operator kernels appearing in nodes of type:

After it has walked over the tree, it creates an instance of PauliAveraging for each distinct state and calls the build() method with the kernel operators associated with the state. It collects all created protocols into a ProtocolList object to be returned.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Values for the parameters in the computable expression.

  • computable (ComputableNode) – A root node of a computable expression tree.

  • exclude (Optional[Callable[[ComputableNode], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

  • noise_mitigation (Optional[NoiseMitigation], default: None) – The noise mitigation instance containing pre and post mitigation strategies.

  • *args – Arguments passed to the constructor of PauliAveraging.

  • **kwargs – Keyword arguments passed to the constructor of PauliAveraging.

Returns:

ProtocolList – A list, containing all the newly instantiated and built protocols.

clear()

Resets the internal state of the object by clearing all stored data.

This method clears all stored data including state hashes, operator hashes, measurement setups, parameters, and associated dataframes and circuits.

Returns:

PauliAveraging – self.

cost()

Calculate a simple cost metric running the protocol.

The cost is calculated as the sum of the depth of each circuit multiplied by the number of shots.

Returns:

int – The cost value as an integer.

credits(syntax_checker=None, use_websocket=None)

Evaluate an approximate cost for the measurement circuits built in Quantinuum credits.

Syntax checker will usually be automatically selected, but in some cases needs to be provided. If the measurement circuits are not built yet, the credits will be zero.

Note

This works only with QuantinuumBackend compatible backends.

Parameters:
  • syntax_checker (Optional[str], default: None) – Which syntax checker to use. The default is None.

  • use_websocket (Optional[bool], default: None) – Whether to use a web connection.

Returns:

float – The total cost in Quantinuum credits to run the circuits.

dataframe_circuit_shot()

Create a pandas DataFrame with circuit, shot, and depth information.

Returns:

DataFrame – A pandas DataFrame containing the circuit, shot, and depth information.

dataframe_measurements()

Create a DataFrame consisting of computational details.

Returns:

DataFrame – A pandas DataFrame with columns 'pauli_string', 'mean', and 'stderr'. Each row represents a unique Pauli string and its associated mean and standard error.

dataframe_partitioning()

Create a DataFrame consisting of partitioning info.

Returns:

DataFrame – A pandas DataFrame with columns 'pauli_string', 'circ_index', and 'circ_name'. Each row represents a Pauli string and its circuit index pairs.

dump(file)

Save the object to a file using pickle.

Parameters:

file (Union[str, BinaryIO]) – The file path or file object to write the pickled data to.

Return type:

None

dumps()

Returns the object pickled as a bytes object.

Returns:

bytes – The object’s state pickled as a bytes object.

evaluate_expectation_uvalue(state, kernel)

Evaluates the expectation value of a Hermitian kernel with linear error propagation theory.

Similarly to evaluate_expectation_value(), this can be only performed if before calling this protocol has been built for the state and kernel (or other operators composed of the same Pauli strings).

Note

It is assumed the measurements for each Pauli strings are independent, that is not generally the case if measurement reduction is applied.

Parameters:
  • state (GeneralAnsatz) – The quantum state for which the expectation value of the kernel is to be calculated.

  • kernel (QubitOperator) – The operator for which the expectation value is being computed.

Returns:

ufloat – The expectation value of the kernel with respect to the given state with standard error.

evaluate_expectation_value(state, kernel)

Evaluates the provided expectation value.

Computes the expectation value with the kernel and state provided.

This method can only be performed if, prior to calling this method, the protocol has been built for the input state and kernel (or other operators composed of the same Pauli strings), and the protocol has also been run.

Parameters:
  • state (GeneralAnsatz) – The quantum state for which the expectation value of the kernel is to be calculated.

  • kernel (QubitOperator) – The operator for which the expectation value is being computed.

Returns:

float – The expectation value of the kernel with respect to the given state.

get_circuits()

Returns the quantum circuits built for this protocol.

Returns:

List[Circuit] – List of circuits.

get_circuitshots()

Generate the circuit shot pairs.

Yields:

Pair of circuit and the associated number of shots.

Return type:

Iterator[CircuitShots]

get_evaluator(allow_partial=False)

Returns an evaluator function to evaluate quantum computables.

This method creates and returns a function (evaluator) that takes in a specific quantum computable and evaluates it based on its type.

Quantum computables the returned evaluator can handle:

Parameters:

allow_partial (bool, default: False) – If False, evaluation will fail when an unsupported computable node is encountered. If True, unsupported nodes will be skipped.

Note

This evaluator works for quantum computables the protocol has been built from.

Raises:

NotImplementedError – If an unsupported computable is encountered, and allow_partial==False.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(qc, compile_symbolic=False, *args, **kwargs)

Returns an end-to-end executor function for a quantum computable.

All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:

Note

At every call of the returned function the internal state of the protocol changes.

Parameters:
  • qc (ComputableNode) – The quantum computable node to be measured and evaluated at every call of the returned function.

  • compile_symbolic (bool, default: False) – If True, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. If False, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper when compile_symbolic=True, because circuit compilation cannot perform optimizations based on numerical parameter values. The advantage of this case is that compilation only takes place once.

Returns:

Callable[[Union[SymbolDict, Dict]], Any] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result.

get_shots()

Returns the number shots to be used for each circuit.

Returns:

List[int] – List of number of shots, the length of this list is the same as the number of circuits.

property is_built: bool

Boolean flag indicating if the instance has been built.

Returns:

True if the build() method has been successfully invoked, otherwise False.

property is_numeric: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

False if any built measurement circuit contains unsubstituted symbols, otherwise True.

property is_run: bool

Boolean flag indicating if the instance has been run.

Returns:

True if the run() method has been successfully invoked, otherwise False.

property is_symbolic: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

True if any built measurement circuit contains unsubstituted symbols, otherwise False.

launch(*args, **kwargs)

Launch the circuits to the backend and return the handles for the results.

This method processes all the circuits and returns a list of ResultHandle objects representing the handles for the results.

Parameters:
  • *args – Additional arguments to be passed to self.backend.process_circuits().

  • **kwargs – Additional keyword arguments to be passed to self.backend.process_circuits().

Returns:

List[ResultHandle] – A list of pytket ResultHandle objects representing the handles for the launched circuits.

classmethod load(file, *args, **kwargs)

Load a pickled object from a file.

Parameters:
  • file (Union[str, BinaryIO]) – The file path or file object to load the pickled data from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

classmethod loads(pickled_data, *args, **kwargs)

Load a pickled object from a bytes object.

Parameters:
  • pickled_data (bytes) – The pickled data to load the object from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

property n_circuit: int

Returns the total number of circuits.

rebuild(*args, **kwargs)

Rebuild the internal data structure.

It is equivalent to clear().build(*args, **kwargs).

Parameters:
  • *args (Any) – Arguments to be passed to build().

  • **kwargs (Any) – Keyword arguments to be passed to build().

Returns:

TypeVar(TBuildClearMixin, bound= BuildClearMixin) – self.

retrieve(source, *args, **kwargs)

Retrieve distributions from the backend for the given source.

If the source is a list of pytket ResultHandle, the distributions are retrieved using self.backend.get_results() method. If the source is a list of pytket BackendResult, it is assumed that the results are already provided.

Parameters:
  • source (Union[List[ResultHandle], List[BackendResult]]) – A list of pytket ResultHandle or BackendResult objects representing the source of the distributions.

  • **kwargs – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

PauliAveraging – Returns self instance.

run(*args, **kwargs)

Run the protocol and waiting for the results.

This method executes the following steps: 1. Launches the measurement circuits to obtain the circuit handles. 2. Retrieves the measurement distributions using the circuit handles.

Parameters:
  • *args (Any) – Arguments to be passed to launch().

  • **kwargs (Any) – Keyword arguments to be passed to launch().

Returns:

TypeVar(TLaunchRetrieveMixin, bound= LaunchRetrieveMixin) – self.

run_mitex(mitex, characterisation)

Run via Qermit MitEx instance with provided characterisation.

The following steps will be executed: Step 1: State and Pauli strings are converted to ObservableExperiment experiments. Step 2: The experiments are run via the MitEx instance. Step 3: Results are processed and internal data structures are updated.

Parameters:
  • mitex (MitEx) – The instance of MitEx to run.

  • characterisation (Dict) – The characterisation to use for the run.

Returns:

PauliAveraging – An instance of the class with updated data.

run_mitres(mitres, characterisation)

Run via Qermit MitRes instance with provided characterisation.

The following steps will be executed: Step 1: circuits and shots will be generated and passed to MitRes instance to run. Step 2: the backend results from the MitRes run is retrieved and internal data is updated.

Parameters:
  • mitres (MitRes) – The instance of MitRes to run.

  • characterisation (Dict) – The characterisation to use for the run.

Returns:

PauliAveraging – An instance of the class with updated data.

class HadamardTest(backend, shots_per_circuit=8000)

Bases: ProtocolListItem, PartiallyPickleable, ComputableCompliantMixin

Calculate the expectation value of a qubit operator using Hadamard tests.

Given an operator as a linear combination of Pauli strings, \(H = \sum_i c_i P_i\), computes the expectation value \(\langle H \rangle\) by performing a set of Hadamard tests to measure the real expectation value of each pauli string (see also the wikipedia article).

Parameters:
  • backend (Backend) – The backend to use for quantum computations.

  • shots_per_circuit (int, default: 8000) – Number of shots for each circuit.

build(parameters, state, *operators, optimisation_level=1)

Builds Hadamard test measurement circuits for each Pauli string.

Note

The coefficients in the operators are ignored.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – A dictionary or SymbolDict containing the parameter values for the circuits.

  • state (GeneralAnsatz) – Parametrized input state.

  • operators (QubitOperator) – Qubit operators, the Pauli strings in these QubitOperator objects are used to generate measurement circuits.

  • optimisation_level (int, default: 1) – Passed to the backend’s get_compiled_circuits() method.

Returns:

TypeVar(T, bound= HadamardTest) – Self instance.

build_from(parameters, computable, exclude=None)

Build the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and collects all qubit operators appearing in nodes of type:

After it has walked over the tree, it calls the build method.

Raises:

NotImplementedError – If not all ExpectationValue nodes in the computable tree contain the same state.

Parameters:
Returns:

HadamardTest – The modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)

Build a ProtocolList based on the given parameters and a computable expression.

This method walks over the computable expression tree and collects all qubit operator kernels appearing in nodes of type:

After walking over the tree, it creates an instance of HadamardTest for each distinct state and calls the build() method with the kernel operators associated with the state. It collects all created protocols into a ProtocolList object to be returned.

Parameters:
Returns:

ProtocolListProtocolList of the newly instantiated and built protocols.

clear()

Resets the internal state of the object by clearing all stored data.

This method clears all stored data including state hashes, operator hashes, measurement setups, parameters, and associated dataframes and circuits.

Returns:

TypeVar(T, bound= HadamardTest) – self.

cost()

Calculate a simple cost metric running the protocol.

The cost is calculated as the sum of the depth of each circuit multiplied by the number of shots.

Returns:

int – The cost value as an integer.

credits(syntax_checker=None, use_websocket=None)

Evaluate an approximate cost for the measurement circuits built in Quantinuum credits.

Syntax checker will usually be automatically selected, but in some cases needs to be provided. If the measurement circuits are not built yet, the credits will be zero.

Note

This works only with QuantinuumBackend compatible backends.

Parameters:
  • syntax_checker (Optional[str], default: None) – Which syntax checker to use. The default is None.

  • use_websocket (Optional[bool], default: None) – Whether to use a web connection.

Returns:

float – The total cost in Quantinuum credits to run the circuits.

dataframe_circuit_shot()

Create a pandas DataFrame with circuit, shot, and depth information.

Returns:

DataFrame – A pandas DataFrame containing the circuit, shot, and depth information.

dataframe_measurements()

Create a DataFrame consisting of computational details.

Returns:

DataFrame – A pandas DataFrame with columns 'pauli_string', 'mean', and 'stderr'. Each row represents a unique Pauli string and its associated mean and standard error.

dump(file)

Save the object to a file using pickle.

Parameters:

file (Union[str, BinaryIO]) – The file path or file object to write the pickled data to.

Return type:

None

dumps()

Returns the object pickled as a bytes object.

Returns:

bytes – The object’s state pickled as a bytes object.

evaluate_expectation_value(state, kernel)

Evaluates the provided expectation value.

Computes the expectation value with the kernel and state provided.

This method can only be performed if, prior to calling this method, the protocol has been built for the input state and kernel (or other operators composed of the same Pauli strings), and the protocol has also been run.

Parameters:
Returns:

float – The expectation value of the kernel with respect to the given state.

get_circuits()

Returns the quantum circuits built for this protocol.

Returns:

List[Circuit] – List of circuits.

get_circuitshots()

Generate the circuit shot pairs.

Yields:

Pair of circuit and the associated number of shots.

Return type:

Iterator[CircuitShots]

get_evaluator(allow_partial=False)

Returns an evaluator function to evaluate quantum computables.

This method creates and returns a function (evaluator) that takes in a specific quantum computable and evaluates it based on its type.

Quantum computables the returned evaluator can handle:

Parameters:

allow_partial (bool, default: False) – If False, evaluation will fail when an unsupported computable node is encountered. If True, unsupported nodes will be skipped.

Raises:

NotImplementedError – If an unsupported computable is encountered, and allow_partial==False.

Note

This evaluator works for quantum computables the protocol has been built from.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(qc, compile_symbolic=False, *args, **kwargs)

Returns an end-to-end executor function for a quantum computable.

All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:

Note

At every call of the returned function the internal state of the protocol changes.

Parameters:
  • qc (ComputableNode) – The quantum computable node to be measured and evaluated at every call of the returned function.

  • compile_symbolic (bool, default: False) – If True, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. If False, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper when compile_symbolic=True, because circuit compilation cannot perform optimizations based on numerical parameter values. The advantage of this case is that compilation only takes place once.

Returns:

Callable[[Union[SymbolDict, Dict]], Any] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result. If the result is not a float, it returns math.nan.

get_shots()

Returns the number shots to be used for each circuit.

Returns:

Iterator[int] – List of number of shots, the length of this list is the same as the number of circuits.

property is_built: bool

Boolean flag indicating if the instance has been built.

Returns:

True if the build() method has been successfully invoked, otherwise False.

property is_numeric: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

False if any built measurement circuit contains unsubstituted symbols, otherwise True.

property is_run: bool

Boolean flag indicating if the instance has been run.

Returns:

True if the run() method has been successfully invoked, otherwise False.

property is_symbolic: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

True if any built measurement circuit contains unsubstituted symbols, otherwise False.

launch(*args, **kwargs)

Launch the circuits to the backend and return the handles for the results.

This method processes all the circuits and returns a list of ResultHandle objects representing the handles for the results.

Parameters:
  • *args – Additional arguments to be passed to self.backend.process_circuits().

  • **kwargs – Additional keyword arguments to be passed to self.backend.process_circuits().

Returns:

List[ResultHandle] – A list of pytket ResultHandle objects representing the handles for the launched circuits.

classmethod load(file, *args, **kwargs)

Load a pickled object from a file.

Parameters:
  • file (Union[str, BinaryIO]) – The file path or file object to load the pickled data from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

classmethod loads(pickled_data, *args, **kwargs)

Load a pickled object from a bytes object.

Parameters:
  • pickled_data (bytes) – The pickled data to load the object from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

property n_circuit: int

Returns the total number of circuits.

rebuild(*args, **kwargs)

Rebuild the internal data structure.

It is equivalent to clear().build(*args, **kwargs).

Parameters:
  • *args (Any) – Arguments to be passed to build().

  • **kwargs (Any) – Keyword arguments to be passed to build().

Returns:

TypeVar(TBuildClearMixin, bound= BuildClearMixin) – self.

retrieve(source, *args, **kwargs)

Retrieve distributions from the backend for the given source.

If the source is a list of pytket ResultHandle, the distributions are retrieved using self.backend.get_results() method. If the source is a list of pytket BackendResult, it is assumed that the results are already provided.

Parameters:
  • source (Union[List[ResultHandle], List[BackendResult]]) – A list of pytket ResultHandle or BackendResult objects representing the source of the distributions.

  • **kwargs – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

TypeVar(T, bound= HadamardTest) – Returns self instance.

run(*args, **kwargs)

Run the protocol and waiting for the results.

This method executes the following steps: 1. Launches the measurement circuits to obtain the circuit handles. 2. Retrieves the measurement distributions using the circuit handles.

Parameters:
  • *args (Any) – Arguments to be passed to launch().

  • **kwargs (Any) – Keyword arguments to be passed to launch().

Returns:

TypeVar(TLaunchRetrieveMixin, bound= LaunchRetrieveMixin) – self.

Protocols for Overlap Squared

class ComputeUncompute(backend, n_shots=8000)

Bases: BaseOverlapSquaredProtocol

Calculates the overlap squared with the compute-uncompute method.

For input states \(|{\psi}\rangle = U|{0}\rangle\) and \(|{\phi}\rangle = V|{0}\rangle\), prepares the state \(U^\dagger V|{0}\rangle\). The overlap squared \(|\langle{\psi|\phi}\rangle|^2\) is then given by the probability of measuring a vacuum state \(|{0}\rangle\). See https://arxiv.org/abs/1810.02327.

Supports calculation of overlap squared of the form: \(|\langle\psi|cP|\phi\rangle|^2\), where \(P\) is a Pauli word and \(c\) is a numeric constant.

Parameters:
  • backend (Backend) – The backend to use for quantum computations.

  • n_shots (int, default: 8000) – Number of shots to perform.

build(parameters, bra_state, ket_state, kernel=None, optimisation_level=1)

Builds the necessary circuits and measurement data.

Note

Any coefficient in the operator kernel is ignored.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameter values for the circuits.

  • bra_state (GeneralAnsatz) – Left-hand state.

  • ket_state (GeneralAnsatz) – Right-hand state.

  • kernel (Union[QubitOperator, QubitOperatorString, None], default: None) – Optional operator kernel. Must be a single Pauli string.

  • optimization_level – Passed as the optimisation_level arg to the backend’s get_compiled_circuits() method.

  • optimisation_level (int, default: 1)

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Self instance after building the necessary circuits and measurement data.

build_from(parameters, computable, exclude=None)

Builds the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and calls the build() method when it encounters a node of type OverlapSquared.

Parameters:
Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Returns the modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)

Build a list of protocols based on the given parameters and computable expression.

This method walks over the computable expression tree and collects leaf nodes of type:

After it has walked over the tree, it creates an instance of this protocol for each distinct bra, ket, kernel trio and calls the build() method. It collects all created protocols into a ProtocolList object to be returned.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Values for the parameters in the computable expression.

  • computable (ComputableNode) – A root node of a computable expression tree.

  • exclude (Optional[Callable[[ComputableNode], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

  • *args – Arguments passed to the constructor of the overlap squared protocol.

  • **kwargs – Keyword arguments passed to the constructor of the overlap squared protocol.

Returns:

ProtocolList – A list, containing all the newly instantiated and built protocols.

circuit: Optional[Circuit]
clear()

Resets the internal state of the object by clearing all stored data.

This method clears all stored data including state hashes, operator hashes, measurement setups, parameters, and associated dataframes and circuits.

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – self.

cost()

Calculate a simple cost metric running the protocol.

The cost is calculated as the sum of the depth of each circuit multiplied by the number of shots.

Returns:

int – The cost value as an integer.

credits(syntax_checker=None, use_websocket=None)

Evaluate an approximate cost for the measurement circuits built in Quantinuum credits.

Syntax checker will usually be automatically selected, but in some cases needs to be provided. If the measurement circuits are not built yet, the credits will be zero.

Note

This works only with QuantinuumBackend compatible backends.

Parameters:
  • syntax_checker (Optional[str], default: None) – Which syntax checker to use. The default is None.

  • use_websocket (Optional[bool], default: None) – Whether to use a web connection.

Returns:

float – The total cost in Quantinuum credits to run the circuits.

dataframe_circuit_shot()

Create a pandas DataFrame with circuit, shot, and depth information.

Returns:

DataFrame – A pandas DataFrame containing the circuit, shot, and depth information.

dump(file)

Save the object to a file using pickle.

Parameters:

file (Union[str, BinaryIO]) – The file path or file object to write the pickled data to.

Return type:

None

dumps()

Returns the object pickled as a bytes object.

Returns:

bytes – The object’s state pickled as a bytes object.

evaluate_overlap_squared(bra_state, ket_state, kernel)

Evaluates the overlap squared for given states and kernel.

Parameters:

Note

Input states and pauli string in the kernel need to match with the states and pauli string the circuit was built for to correctly interpret the circuit output distribution.

Returns:

Overlap squared.

get_circuits()

Returns the quantum circuits built for this protocol.

Returns:

List[Circuit] – List of circuits.

get_circuitshots()

Generate the circuit shot pairs.

Yields:

Pair of circuit and the associated number of shots.

Return type:

Iterator[CircuitShots]

get_evaluator(allow_partial=False)

Returns an evaluator function to evaluate quantum computables.

This method creates and returns a function (evaluator) that takes in a specific quantum computable and evaluates it based on its type.

Quantum computables the returned evaluator can handle:

Parameters:

allow_partial (bool, default: False) – If False, evaluation will fail when an unsupported computable node is encountered. If True, unsupported nodes will be skipped.

Raises:

NotImplementedError – If an unsupported computable is encountered, and allow_partial==False.

Note

This evaluator works for quantum computables the protocol has been built from.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(c, compile_symbolic=False, *args, **kwargs)

Returns an end-to-end executor function for a quantum computable.

Note

All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be OverlapSquared.

Note

At every call of the returned function the internal state of the protocol changes.

Parameters:
  • c (ComputableNode) – The quantum computable node to be measured and evaluated at every call of the returned function.

  • compile_symbolic (bool, default: False) – If True, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. If False, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper when compile_symbolic=True, because circuit compilation cannot perform optimizations based on numerical parameter values. The advantage of this case is that compilation only takes place once.

  • args (Any)

  • kwargs (Any)

Returns:

Callable[[Union[SymbolDict, Dict]], Any] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result. If the result is not a float, it returns math.nan.

get_shots()

Returns the number shots to be used for each circuit.

Returns:

List[int] – List of number of shots, the length of this list is the same as the number of circuits.

property is_built: bool

Boolean flag indicating if the instance has been built.

Returns:

True if the build() method has been successfully invoked, otherwise False.

property is_numeric: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

False if any built measurement circuit contains unsubstituted symbols, otherwise True.

property is_run: bool

Boolean flag indicating if the instance has been run.

Returns:

True if the run() method has been successfully invoked, otherwise False.

property is_symbolic: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

True if any built measurement circuit contains unsubstituted symbols, otherwise False.

launch(*args, **kwargs)

Launch the circuits to the backend and return the handles for the results.

This method processes all the circuits and returns a list of ResultHandle objects representing the handles for the results.

Parameters:
  • *args (Any) – Additional arguments to be passed to self.backend.process_circuits().

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.process_circuits().

Returns:

List[ResultHandle] – A list of pytket ResultHandle objects representing the handles for the launched circuits.

classmethod load(file, *args, **kwargs)

Load a pickled object from a file.

Parameters:
  • file (Union[str, BinaryIO]) – The file path or file object to load the pickled data from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

classmethod loads(pickled_data, *args, **kwargs)

Load a pickled object from a bytes object.

Parameters:
  • pickled_data (bytes) – The pickled data to load the object from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

property n_circuit: int

Returns the total number of circuits.

rebuild(*args, **kwargs)

Rebuild the internal data structure.

It is equivalent to clear().build(*args, **kwargs).

Parameters:
  • *args (Any) – Arguments to be passed to build().

  • **kwargs (Any) – Keyword arguments to be passed to build().

Returns:

TypeVar(TBuildClearMixin, bound= BuildClearMixin) – self.

retrieve(source, **kwargs)

Retrieve distributions from the backend for the given source.

If the source is a list of pytket ResultHandle, the distributions are retrieved using self.backend.get_results() method. If the source is a list of pytket BackendResult, it is assumed that the results are already provided.

Parameters:
  • source (Union[List[ResultHandle], List[BackendResult]]) – A list of pytket ResultHandle or BackendResult objects representing the source of the distributions.

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Returns self instance.

run(*args, **kwargs)

Run the protocol and waiting for the results.

This method executes the following steps: 1. Launches the measurement circuits to obtain the circuit handles. 2. Retrieves the measurement distributions using the circuit handles.

Parameters:
  • *args (Any) – Arguments to be passed to launch().

  • **kwargs (Any) – Keyword arguments to be passed to launch().

Returns:

TypeVar(TLaunchRetrieveMixin, bound= LaunchRetrieveMixin) – self.

class DestructiveSwapTest(backend, n_shots=8000)

Bases: BaseOverlapSquaredProtocol

Calculate the overlap squared with the destructive swap test.

Based on https://arxiv.org/abs/1303.6814. Prepares both bra and ket states in parallel and performs a destructive swap test i.e. no ancilla qubit is required. The test succeeds when a bitwise AND between the output bra and ket state registers has even parity. The probability of success is given by \(\frac{1}{2}(1+|\langle{\psi|\phi}\rangle|^2)\).

The bra state register is used as the control, while the ket register is the target.

Supports calculation of overlap squared of the form: \(|\langle\psi|cP|\phi\rangle|^2\), where \(P\) is a Pauli word and \(c\) is a numeric constant.

Parameters:
  • backend (Backend) – The backend to use for quantum computations.

  • n_shots (int, default: 8000) – Number of shots to perform.

build(parameters, bra_state, ket_state, kernel=None, optimisation_level=1)

Builds the necessary circuits and measurement data.

Note

Any coefficient in the operator kernel is ignored.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameter values for the circuits.

  • bra_state (GeneralAnsatz) – Left-hand state.

  • ket_state (GeneralAnsatz) – Right-hand state.

  • kernel (Union[QubitOperator, QubitOperatorString, None], default: None) – Optional operator kernel. Must be a single Pauli string.

  • optimization_level – Passed as the optimisation_level arg to the backend’s get_compiled_circuits() method.

  • optimisation_level (int, default: 1)

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Self instance after building the necessary circuits and measurement data.

build_from(parameters, computable, exclude=None)

Builds the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and calls the build() method when it encounters a node of type OverlapSquared.

Parameters:
Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Returns the modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)

Build a list of protocols based on the given parameters and computable expression.

This method walks over the computable expression tree and collects leaf nodes of type:

After it has walked over the tree, it creates an instance of this protocol for each distinct bra, ket, kernel trio and calls the build() method. It collects all created protocols into a ProtocolList object to be returned.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Values for the parameters in the computable expression.

  • computable (ComputableNode) – A root node of a computable expression tree.

  • exclude (Optional[Callable[[ComputableNode], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

  • *args – Arguments passed to the constructor of the overlap squared protocol.

  • **kwargs – Keyword arguments passed to the constructor of the overlap squared protocol.

Returns:

ProtocolList – A list, containing all the newly instantiated and built protocols.

circuit: Optional[Circuit]
clear()

Resets the internal state of the object by clearing all stored data.

This method clears all stored data including state hashes, operator hashes, measurement setups, parameters, and associated dataframes and circuits.

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – self.

cost()

Calculate a simple cost metric running the protocol.

The cost is calculated as the sum of the depth of each circuit multiplied by the number of shots.

Returns:

int – The cost value as an integer.

credits(syntax_checker=None, use_websocket=None)

Evaluate an approximate cost for the measurement circuits built in Quantinuum credits.

Syntax checker will usually be automatically selected, but in some cases needs to be provided. If the measurement circuits are not built yet, the credits will be zero.

Note

This works only with QuantinuumBackend compatible backends.

Parameters:
  • syntax_checker (Optional[str], default: None) – Which syntax checker to use. The default is None.

  • use_websocket (Optional[bool], default: None) – Whether to use a web connection.

Returns:

float – The total cost in Quantinuum credits to run the circuits.

dataframe_circuit_shot()

Create a pandas DataFrame with circuit, shot, and depth information.

Returns:

DataFrame – A pandas DataFrame containing the circuit, shot, and depth information.

dump(file)

Save the object to a file using pickle.

Parameters:

file (Union[str, BinaryIO]) – The file path or file object to write the pickled data to.

Return type:

None

dumps()

Returns the object pickled as a bytes object.

Returns:

bytes – The object’s state pickled as a bytes object.

evaluate_overlap_squared(bra_state, ket_state, kernel)

Evaluates the overlap squared for given states and kernel.

Parameters:

Note

Input states and pauli string in the kernel need to match with the states and pauli string the circuit was built for to correctly interpret the circuit output distribution.

Returns:

Overlap squared.

get_circuits()

Returns the quantum circuits built for this protocol.

Returns:

List[Circuit] – List of circuits.

get_circuitshots()

Generate the circuit shot pairs.

Yields:

Pair of circuit and the associated number of shots.

Return type:

Iterator[CircuitShots]

get_evaluator(allow_partial=False)

Returns an evaluator function to evaluate quantum computables.

This method creates and returns a function (evaluator) that takes in a specific quantum computable and evaluates it based on its type.

Quantum computables the returned evaluator can handle:

Parameters:

allow_partial (bool, default: False) – If False, evaluation will fail when an unsupported computable node is encountered. If True, unsupported nodes will be skipped.

Raises:

NotImplementedError – If an unsupported computable is encountered, and allow_partial==False.

Note

This evaluator works for quantum computables the protocol has been built from.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(c, compile_symbolic=False, *args, **kwargs)

Returns an end-to-end executor function for a quantum computable.

Note

All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be OverlapSquared.

Note

At every call of the returned function the internal state of the protocol changes.

Parameters:
  • c (ComputableNode) – The quantum computable node to be measured and evaluated at every call of the returned function.

  • compile_symbolic (bool, default: False) – If True, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. If False, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper when compile_symbolic=True, because circuit compilation cannot perform optimizations based on numerical parameter values. The advantage of this case is that compilation only takes place once.

  • args (Any)

  • kwargs (Any)

Returns:

Callable[[Union[SymbolDict, Dict]], Any] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result. If the result is not a float, it returns math.nan.

get_shots()

Returns the number shots to be used for each circuit.

Returns:

List[int] – List of number of shots, the length of this list is the same as the number of circuits.

property is_built: bool

Boolean flag indicating if the instance has been built.

Returns:

True if the build() method has been successfully invoked, otherwise False.

property is_numeric: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

False if any built measurement circuit contains unsubstituted symbols, otherwise True.

property is_run: bool

Boolean flag indicating if the instance has been run.

Returns:

True if the run() method has been successfully invoked, otherwise False.

property is_symbolic: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

True if any built measurement circuit contains unsubstituted symbols, otherwise False.

launch(*args, **kwargs)

Launch the circuits to the backend and return the handles for the results.

This method processes all the circuits and returns a list of ResultHandle objects representing the handles for the results.

Parameters:
  • *args (Any) – Additional arguments to be passed to self.backend.process_circuits().

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.process_circuits().

Returns:

List[ResultHandle] – A list of pytket ResultHandle objects representing the handles for the launched circuits.

classmethod load(file, *args, **kwargs)

Load a pickled object from a file.

Parameters:
  • file (Union[str, BinaryIO]) – The file path or file object to load the pickled data from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

classmethod loads(pickled_data, *args, **kwargs)

Load a pickled object from a bytes object.

Parameters:
  • pickled_data (bytes) – The pickled data to load the object from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

property n_circuit: int

Returns the total number of circuits.

rebuild(*args, **kwargs)

Rebuild the internal data structure.

It is equivalent to clear().build(*args, **kwargs).

Parameters:
  • *args (Any) – Arguments to be passed to build().

  • **kwargs (Any) – Keyword arguments to be passed to build().

Returns:

TypeVar(TBuildClearMixin, bound= BuildClearMixin) – self.

retrieve(source, **kwargs)

Retrieve distributions from the backend for the given source.

If the source is a list of pytket ResultHandle, the distributions are retrieved using self.backend.get_results() method. If the source is a list of pytket BackendResult, it is assumed that the results are already provided.

Parameters:
  • source (Union[List[ResultHandle], List[BackendResult]]) – A list of pytket ResultHandle or BackendResult objects representing the source of the distributions.

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Returns self instance.

run(*args, **kwargs)

Run the protocol and waiting for the results.

This method executes the following steps: 1. Launches the measurement circuits to obtain the circuit handles. 2. Retrieves the measurement distributions using the circuit handles.

Parameters:
  • *args (Any) – Arguments to be passed to launch().

  • **kwargs (Any) – Keyword arguments to be passed to launch().

Returns:

TypeVar(TLaunchRetrieveMixin, bound= LaunchRetrieveMixin) – self.

class SwapTest(backend, n_shots=8000)

Bases: BaseOverlapSquaredProtocol

Calculate the overlap squared with the canonical swap test.

Input states \(|\psi\rangle\) and \(|\phi\rangle\) are prepared in parallel alongside an ancilla qubit to generate the state \(|0, \psi, \phi\rangle\). A swap operation between \(\psi\) and \(\phi\) is controlled on the ancilla and wrapped by Hadamard gates so that the probability of measuring \(|0\rangle\) on the ancilla is given by \(\frac{1}{2}(1+|\langle\psi|\phi\rangle|^2)\). See https://en.wikipedia.org/wiki/Swap_test.

Supports calculation of overlap squared of the form: \(|\langle\psi|cP|\phi\rangle|^2\), where \(P\) is a Pauli word and \(c\) is a numeric constant.

Parameters:
  • backend (Backend) – The backend to use for quantum computations.

  • n_shots (int, default: 8000) – Number of shots to perform.

build(parameters, bra_state, ket_state, kernel=None, optimisation_level=1)

Builds the necessary circuits and measurement data.

Note

Any coefficient in the operator kernel is ignored.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameter values for the circuits.

  • bra_state (GeneralAnsatz) – Left-hand state.

  • ket_state (GeneralAnsatz) – Right-hand state.

  • kernel (Union[QubitOperator, QubitOperatorString, None], default: None) – Optional operator kernel. Must be a single Pauli string.

  • optimization_level – Passed as the optimisation_level arg to the backend’s get_compiled_circuits() method.

  • optimisation_level (int, default: 1)

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Self instance after building the necessary circuits and measurement data.

build_from(parameters, computable, exclude=None)

Builds the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and calls the build() method when it encounters a node of type OverlapSquared.

Parameters:
Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Returns the modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)

Build a list of protocols based on the given parameters and computable expression.

This method walks over the computable expression tree and collects leaf nodes of type:

After it has walked over the tree, it creates an instance of this protocol for each distinct bra, ket, kernel trio and calls the build() method. It collects all created protocols into a ProtocolList object to be returned.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Values for the parameters in the computable expression.

  • computable (ComputableNode) – A root node of a computable expression tree.

  • exclude (Optional[Callable[[ComputableNode], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

  • *args – Arguments passed to the constructor of the overlap squared protocol.

  • **kwargs – Keyword arguments passed to the constructor of the overlap squared protocol.

Returns:

ProtocolList – A list, containing all the newly instantiated and built protocols.

circuit: Optional[Circuit]
clear()

Resets the internal state of the object by clearing all stored data.

This method clears all stored data including state hashes, operator hashes, measurement setups, parameters, and associated dataframes and circuits.

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – self.

cost()

Calculate a simple cost metric running the protocol.

The cost is calculated as the sum of the depth of each circuit multiplied by the number of shots.

Returns:

int – The cost value as an integer.

credits(syntax_checker=None, use_websocket=None)

Evaluate an approximate cost for the measurement circuits built in Quantinuum credits.

Syntax checker will usually be automatically selected, but in some cases needs to be provided. If the measurement circuits are not built yet, the credits will be zero.

Note

This works only with QuantinuumBackend compatible backends.

Parameters:
  • syntax_checker (Optional[str], default: None) – Which syntax checker to use. The default is None.

  • use_websocket (Optional[bool], default: None) – Whether to use a web connection.

Returns:

float – The total cost in Quantinuum credits to run the circuits.

dataframe_circuit_shot()

Create a pandas DataFrame with circuit, shot, and depth information.

Returns:

DataFrame – A pandas DataFrame containing the circuit, shot, and depth information.

dump(file)

Save the object to a file using pickle.

Parameters:

file (Union[str, BinaryIO]) – The file path or file object to write the pickled data to.

Return type:

None

dumps()

Returns the object pickled as a bytes object.

Returns:

bytes – The object’s state pickled as a bytes object.

evaluate_overlap_squared(bra_state, ket_state, kernel)

Evaluates the overlap squared for given states and kernel.

Parameters:

Note

Input states and pauli string in the kernel need to match with the states and pauli string the circuit was built for to correctly interpret the circuit output distribution.

Returns:

Overlap squared.

get_circuits()

Returns the quantum circuits built for this protocol.

Returns:

List[Circuit] – List of circuits.

get_circuitshots()

Generate the circuit shot pairs.

Yields:

Pair of circuit and the associated number of shots.

Return type:

Iterator[CircuitShots]

get_evaluator(allow_partial=False)

Returns an evaluator function to evaluate quantum computables.

This method creates and returns a function (evaluator) that takes in a specific quantum computable and evaluates it based on its type.

Quantum computables the returned evaluator can handle:

Parameters:

allow_partial (bool, default: False) – If False, evaluation will fail when an unsupported computable node is encountered. If True, unsupported nodes will be skipped.

Raises:

NotImplementedError – If an unsupported computable is encountered, and allow_partial==False.

Note

This evaluator works for quantum computables the protocol has been built from.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(c, compile_symbolic=False, *args, **kwargs)

Returns an end-to-end executor function for a quantum computable.

Note

All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be OverlapSquared.

Note

At every call of the returned function the internal state of the protocol changes.

Parameters:
  • c (ComputableNode) – The quantum computable node to be measured and evaluated at every call of the returned function.

  • compile_symbolic (bool, default: False) – If True, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. If False, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper when compile_symbolic=True, because circuit compilation cannot perform optimizations based on numerical parameter values. The advantage of this case is that compilation only takes place once.

  • args (Any)

  • kwargs (Any)

Returns:

Callable[[Union[SymbolDict, Dict]], Any] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result. If the result is not a float, it returns math.nan.

get_shots()

Returns the number shots to be used for each circuit.

Returns:

List[int] – List of number of shots, the length of this list is the same as the number of circuits.

property is_built: bool

Boolean flag indicating if the instance has been built.

Returns:

True if the build() method has been successfully invoked, otherwise False.

property is_numeric: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

False if any built measurement circuit contains unsubstituted symbols, otherwise True.

property is_run: bool

Boolean flag indicating if the instance has been run.

Returns:

True if the run() method has been successfully invoked, otherwise False.

property is_symbolic: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

True if any built measurement circuit contains unsubstituted symbols, otherwise False.

launch(*args, **kwargs)

Launch the circuits to the backend and return the handles for the results.

This method processes all the circuits and returns a list of ResultHandle objects representing the handles for the results.

Parameters:
  • *args (Any) – Additional arguments to be passed to self.backend.process_circuits().

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.process_circuits().

Returns:

List[ResultHandle] – A list of pytket ResultHandle objects representing the handles for the launched circuits.

classmethod load(file, *args, **kwargs)

Load a pickled object from a file.

Parameters:
  • file (Union[str, BinaryIO]) – The file path or file object to load the pickled data from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

classmethod loads(pickled_data, *args, **kwargs)

Load a pickled object from a bytes object.

Parameters:
  • pickled_data (bytes) – The pickled data to load the object from.

  • *args (Any) – Additional arguments passed to the class constructor.

  • **kwargs (Any) – Additional keyword arguments passed to the class constructor.

Returns:

TypeVar(T, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

property n_circuit: int

Returns the total number of circuits.

rebuild(*args, **kwargs)

Rebuild the internal data structure.

It is equivalent to clear().build(*args, **kwargs).

Parameters:
  • *args (Any) – Arguments to be passed to build().

  • **kwargs (Any) – Keyword arguments to be passed to build().

Returns:

TypeVar(TBuildClearMixin, bound= BuildClearMixin) – self.

retrieve(source, **kwargs)

Retrieve distributions from the backend for the given source.

If the source is a list of pytket ResultHandle, the distributions are retrieved using self.backend.get_results() method. If the source is a list of pytket BackendResult, it is assumed that the results are already provided.

Parameters:
  • source (Union[List[ResultHandle], List[BackendResult]]) – A list of pytket ResultHandle or BackendResult objects representing the source of the distributions.

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

TypeVar(T, bound= BaseOverlapSquaredProtocol) – Returns self instance.

run(*args, **kwargs)

Run the protocol and waiting for the results.

This method executes the following steps: 1. Launches the measurement circuits to obtain the circuit handles. 2. Retrieves the measurement distributions using the circuit handles.

Parameters:
  • *args (Any) – Arguments to be passed to launch().

  • **kwargs (Any) – Keyword arguments to be passed to launch().

Returns:

TypeVar(TLaunchRetrieveMixin, bound= LaunchRetrieveMixin) – self.

Protocols for Overlaps

class HadamardTestOverlap(backend, shots_per_circuit, direct=False, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_colour_method=GraphColourMethod.Lazy)

Bases: BaseOverlapProtocol

Calculates the overlap of two states using a specialized Hadamard test.

Computes the real or imaginary part of \(\langle A | B \rangle\) where \(|A\rangle = U_A |0\rangle\) using the “linear combination of unitaries” method from https://journals.aps.org/pra/abstract/10.1103/PhysRevA.99.032331 (see figure 2). For direct=True, this method uses the approach from https://iopscience.iop.org/article/10.1088/1367-2630/ab867b to combine ancilla and state register measurements to compute overlaps with kernels.

Parameters:
  • backend (Backend) – The backend to use for quantum computations.

  • shots_per_circuit (int) – Number of shots to perform.

  • direct (bool, default: False) – Relevant for overlaps with non-identity kernels. If True, Pauli words are divided into simultaneously measurable sets and computed using direct measurement of expectation values on the state register.

  • pauli_partition_strategy (Optional[PauliPartitionStrat], default: PauliPartitionStrat.NonConflictingSets) – For direct=True. Strategy to partition Pauli operators.

  • pauli_colour_method (Optional[GraphColourMethod], default: GraphColourMethod.Lazy) – For direct=True. Method to perform graph colouring.

build(parameters, bra_state, ket_state, *operators, component, optimisation_level=1)

Builds and compiles the necessary circuits for computing an overlap.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameter values for the circuits.

  • bra_state (GeneralAnsatz) – Left-hand state.

  • ket_state (GeneralAnsatz) – Right-hand state.

  • operators (QubitOperator) – Operator kernel, default is the identity. Coefficients in the kernel are ignored; only the Pauli strings are used in circuit construction.

  • component (Union[str, NumberType]) – Component of overlap to measure: real, imag, or complex.

  • optimisation_level (int, default: 1) – Passed to the backend’s get_compiled_circuits() method.

Returns:

BaseOverlapProtocol – Self instance.

build_from(parameters, computable, exclude=None)

Builds the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and calls the build() method for leaves of type Overlap, OverlapReal, and OverlapImag.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameters for building.

  • computable (Any) – A root node of a computable expression tree, simply it is a computable expression.

  • exclude (Optional[Callable[[Any], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

Returns:

BaseOverlapProtocol – The modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)

Build a list of protocols based on the given parameters and computable expression.

This method walks over the computable expression tree and collects all qubit operator kernels appearing in nodes of type:

After it has walked over the tree, it creates an instance of HadamardTestOverlap for each distinct bra, ket pair of states, and calls the build() method with the kernel operators associated with the states. It collects all created protocols into a ProtocolList object to be returned.

Parameters:
Returns:

ProtocolList – A list, containing all the newly instantiated and built protocols.

circuits: Optional[List[Circuit]]
clear()

Resets the internal state of the object by clearing all stored data.

This method clears all stored data including state hashes, operator hashes, measurement setups, parameters, and associated dataframes and circuits.

Returns:

BaseOverlapProtocol – self.

cost()

Calculate a simple cost metric running the protocol.

The cost is calculated as the sum of the depth of each circuit multiplied by the number of shots.

Returns:

int – The cost value as an integer.

credits(syntax_checker=None, use_websocket=None)

Evaluate an approximate cost for the measurement circuits built in Quantinuum credits.

Syntax checker will usually be automatically selected, but in some cases needs to be provided. If the measurement circuits are not built yet, the credits will be zero.

Note

This works only with QuantinuumBackend compatible backends.

Parameters:
  • syntax_checker (Optional[str], default: None) – Which syntax checker to use. The default is None.

  • use_websocket (Optional[bool], default: None) – Whether to use a web connection.

Returns:

float – The total cost in Quantinuum credits to run the circuits.

dataframe_circuit_shot()

Create a pandas DataFrame with circuit, shot, and depth information.

Returns:

DataFrame – A pandas DataFrame containing the circuit, shot, and depth information.

evaluate_overlap(bra_state, ket_state, kernel={(): 1.0})

Evaluates the overlap for given states and kernel.

This method can only be performed if, prior to calling this method, the protocol has been built for component='complex', with the same input states and kernel (or other operators composed of the same Pauli strings), and the protocol has also been run.

Parameters:
Returns:

complex – Real part of the overlap.

evaluate_overlap_imag(bra_state, ket_state, kernel={(): 1.0})

Evaluates the imaginary part of the overlap for given states and kernel.

This method can only be performed if, prior to calling this method, the protocol has been built for component='imag' or 'complex', with the same input states and kernel (or other operators composed of the same Pauli strings), and the protocol has also been run.

Parameters:
Returns:

float – Real part of the overlap.

evaluate_overlap_real(bra_state, ket_state, kernel={(): 1.0})

Evaluates the real part of the overlap for given states and kernel.

This method can only be performed if, prior to calling this method, the protocol has been built for component='real' or 'complex', with the same input states and kernel (or other operators composed of the same Pauli strings), and the protocol has also been run.

Parameters:
Returns:

float – Real part of the overlap.

get_circuits()

Returns the quantum circuits built for this protocol.

Returns:

List[Circuit] – List of circuits.

get_circuitshots()

Generate the circuit shot pairs.

Yields:

Pair of circuit and the associated number of shots.

Return type:

Iterator[CircuitShots]

get_evaluator(allow_partial=False)

Returns an evaluator function to evaluate quantum computables.

This method creates and returns a function (evaluator) that takes in a specific quantum computable and evaluates it based on its type.

Quantum computables the returned evaluator can handle:

Parameters:

allow_partial (bool, default: False) – If False, evaluation will fail when an unsupported computable node is encountered. If True, unsupported nodes will be skipped.

Note

This evaluator works for quantum computables the protocol has been built from.

Raises:

NotImplementedError – If an unsupported computable is encountered, and allow_partial==False.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(qc, compile_symbolic=False, *args, **kwargs)

Returns an end-to-end executor function for a quantum computable.

All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:

Note

At every call of the returned function the internal state of the protocol changes.

Parameters:
  • qc (ComputableNode) – The quantum computable node to be measured and evaluated at every call of the returned function.

  • compile_symbolic (bool, default: False) – If True, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. If False, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper when compile_symbolic=True, because circuit compilation cannot perform optimizations based on numerical parameter values. The advantage of this case is that compilation only takes place once.

  • args (Any)

  • kwargs (Any)

Returns:

Callable[[Union[SymbolDict, Dict]], Any] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result. If the result is not a float, it returns math.nan.

get_shots()

Returns the number shots to be used for each circuit.

Returns:

List[int] – List of number of shots, the length of this list is the same as the number of circuits.

property is_built: bool

Boolean flag indicating if the instance has been built.

Returns:

True if the build() method has been successfully invoked, otherwise False.

property is_numeric: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

False if any built measurement circuit contains unsubstituted symbols, otherwise True.

property is_run: bool

Boolean flag indicating if the instance has been run.

Returns:

True if the run() method has been successfully invoked, otherwise False.

property is_symbolic: bool

Boolean flag indicating if the measurement circuits contain free symbols.

Returns:

True if any built measurement circuit contains unsubstituted symbols, otherwise False.

launch(*args, **kwargs)

Launch the circuits to the backend and return the handles for the results.

This method processes all the circuits and returns a list of ResultHandle objects representing the handles for the results.

Parameters:
  • *args (Any) – Additional arguments to be passed to self.backend.process_circuits().

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.process_circuits().

Returns:

List[ResultHandle] – A list of pytket ResultHandle objects representing the handles for the launched circuits.

property n_circuit: int

Returns the total number of circuits.

rebuild(*args, **kwargs)

Rebuild the internal data structure.

It is equivalent to clear().build(*args, **kwargs).

Parameters:
  • *args (Any) – Arguments to be passed to build().

  • **kwargs (Any) – Keyword arguments to be passed to build().

Returns:

TypeVar(TBuildClearMixin, bound= BuildClearMixin) – self.

retrieve(source, **kwargs)

Retrieve distributions from the backend for the given source.

If the source is a list of pytket ResultHandle, the distributions are retrieved using self.backend.get_results() method. If the source is a list of pytket BackendResult, it is assumed that the results are already provided.

Parameters:
  • source (Union[List[ResultHandle], List[BackendResult]]) – A list of pytket ResultHandle or BackendResult objects representing the source of the distributions.

  • **kwargs (Any) – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

BaseOverlapProtocol – Returns self instance.

run(*args, **kwargs)

Run the protocol and waiting for the results.

This method executes the following steps: 1. Launches the measurement circuits to obtain the circuit handles. 2. Retrieves the measurement distributions using the circuit handles.

Parameters:
  • *args (Any) – Arguments to be passed to launch().

  • **kwargs (Any) – Keyword arguments to be passed to launch().

Returns:

TypeVar(TLaunchRetrieveMixin, bound= LaunchRetrieveMixin) – self.

class ComputeUncomputeFactorizedOverlap(backend, shots_per_circuit)

Bases: FactorizedOverlap

Computes the ket and uncomputes the bra to construct the required linear combination on a single state register.

Computes the real or imaginary part of \(\langle A | B \rangle\) where \(|A\rangle = U_A U_\text{ref}|0\rangle\) and \(|B\rangle = U_B U_\text{ref}|0\rangle\) in the manner shown in Figure 2 of https://journals.aps.org/prxquantum/abstract/10.1103/PRXQuantum.4.030307.

This protocol is not compatible with the “direct” operator averaging approach.

Parameters:
  • backend (Backend) – The backend to use for quantum computations.

  • shots_per_circuit (int) – Number of shots to perform.

build(parameters, bra_state, ket_state, *operators, component, optimisation_level=1)

Builds and compiles the necessary circuits for computing an overlap.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameter values for the circuits.

  • bra_state (GeneralAnsatz) – Left-hand state.

  • ket_state (GeneralAnsatz) – Right-hand state.

  • operators (QubitOperator) – Operator kernel, default is the identity. Coefficients in the kernel are ignored; only the Pauli strings are used in circuit construction.

  • component (Union[str, NumberType]) – Component of overlap to measure: real, imag, or complex.

  • optimisation_level (int, default: 1) – Passed to the backend’s get_compiled_circuits() method.

Returns:

BaseOverlapProtocol – Self instance.

build_from(parameters, computable, exclude=None)

Builds the protocol based on given parameters and computable expression.

This method walks over the computable expression tree and calls the build() method for leaves of type Overlap, OverlapReal, and OverlapImag.

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Parameters for building.

  • computable (Any) – A root node of a computable expression tree, simply it is a computable expression.

  • exclude (Optional[Callable[[Any], bool]], default: None) – Optional callable function to exclude certain nodes from processing.

Returns:

BaseOverlapProtocol – The modified instance after building.

classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)

Build a list of protocols based on the given parameters and computable expression.

This method walks over the computable expression tree and collects all qubit operator kernels appearing in nodes of type:

After it has walked over the tree, it creates an instance of