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 FactorizedOverlap(backend, shots_per_circuit, direct=False, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_colour_method=GraphColourMethod.Lazy)

Bases: BaseOverlapProtocol

Abstract base class for specialized overlap protocols between ansatzes that factorize into a reference and a number conserving unitary.

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 Figures 1 and 2 of https://journals.aps.org/prxquantum/abstract/10.1103/PRXQuantum.4.030307. These protocols make use of the property that \(U_A |0\rangle = |0\rangle\) to avoid the potentially large controlled state unitaries involved in e.g. HadamardTestOverlap.

Warning

Only ansatzes with the property that \(U_A |0\rangle = |0\rangle\) are compatible with protocols of this type.

Parameters:
  • backend (Backend)

  • shots_per_circuit (int)

  • direct (bool, default: False)

  • pauli_partition_strategy (Optional[PauliPartitionStrat], default: PauliPartitionStrat.NonConflictingSets)

  • pauli_colour_method (Optional[GraphColourMethod], default: GraphColourMethod.Lazy)

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 SwapFactorizedOverlap(backend, shots_per_circuit, direct=False, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_colour_method=GraphColourMethod.Lazy)

Bases: FactorizedOverlap

Uses an ancillary state register to obviate controlled ansatz unitaries.

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 1 of https://journals.aps.org/prxquantum/abstract/10.1103/PRXQuantum.4.030307.

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 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.

Statevector-Based Protocols

class SparseStatevectorProtocol(backend, cache=None, caching_decorator=cached)

Bases: _BaseStatevectorProtocol, EvaluatorRunnerMixin

Protocol for sparse statevector calculations using caching.

Uses an (optionally) externally provided cache-handling class and an external caching decorator to wrap its methods to be cached.

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

  • cache (Optional[Cache], default: None) – A cache-handling class object. If None, ProtocolCache is implicitly instantiated and used.

  • caching_decorator (Callable[[Callable[..., Any]], Callable[..., Any]], default: cached) – A caching decorator, that needs to take both an arbitrary function and a cache-handler as parameters. By default, a function decorator local to the class module is used.

property cache: Cache

Returns the cache-handling object.

cache_hit_report()

Returns a cache hit report in the pandas DataFrame format.

Return type:

Optional[DataFrame]

clear(keep_cache=False)

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

Sets the backend to None, and clears the cache.

Parameters:

keep_cache (bool, default: False) – Whether to keep old cache.

Return type:

None

copy()

Returns a deep copy of the protocol.

Return type:

_BaseStatevectorProtocol

get_evaluator(parameters, allow_partial=True)

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. The returned evaluator handles various computable types, such as expectation values, their derivatives, overlaps, etc.

Quantum computables the returned evaluator can handle:

Parameters:
  • parameters (SymbolDict) – Symbols and their values to be used in the evaluation.

  • allow_partial (bool, default: True) – 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.

Returns:

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

get_runner(qc)

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

All nodes in the quantum computable must be evaluable by this protocol. Supported computable are:

Parameters:

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

Returns:

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

class BackendStatevectorProtocol(backend)

Bases: _BaseStatevectorProtocol

Statevector protocol utilising backend functionality to enable statevector simulations.

Parameters:

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

copy()

Returns a deep copy of the protocol.

Return type:

_BaseStatevectorProtocol

get_evaluator(parameters, allow_partial=True)

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. The returned evaluator handles various computable types, such as expectation values, their derivatives, overlaps, etc.

Quantum computables the returned evaluator can handle:

Parameters:
  • parameters (SymbolDict) – Symbols and their values to be used in the evaluation.

  • allow_partial (bool, default: True) – 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.

Returns:

Callable[[Any], Any] – A function that can evaluates quantum computables. If the Computable is supported by this protocol, it is computed; otherwise, it returns the Computable itself.

get_runner(qc)

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

All nodes in the quantum computable must be evaluable by this protocol. Supported computables are:

Parameters:

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

Returns:

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

class SymbolicProtocol(simplifier=None)

Bases: EvaluatorRunnerMixin

Protocol for statevector calculations using Sympy symbolic evaluation.

Note

This protocol caches the symbolic states, therefore one evaluation might be slow, but subsequent evaluations cost less time.

Parameters:

simplifier (Callable[[Expr], Expr], default: None) – A sympy simplifier that will be applied on the results before substitution, default is None.

clear()

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

Clears runtime auxiliary variables in the protocol.

Return type:

None

get_evaluator(parameters, allow_partial=True)

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. The returned evaluator handles various computable types, such as expectation values, their derivatives, overlaps, etc.

Quantum computables the returned evaluator can handle:

Parameters:
  • parameters (Union[SymbolDict, Dict[Symbol, float]]) – Symbols and their values to be used in the evaluation.

  • allow_partial (bool, default: True) – 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.

Returns:

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

get_runner(qc)

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

All nodes in the quantum computable must be evaluable by this protocol. Supported computables are:

Parameters:

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

Returns:

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

Protocols for Derivatives

class HadamardTestDerivativeOverlap(backend, shots_per_circuit=10000)

Bases: BuildClearMixin, GenerateCircuitShotMixin, LaunchRetrieveMixin, PartiallyPickleable, ComputableCompliantMixin

Calculate the derivative overlap (“Metric tensor”) of a parametrized reference state using an ancilla qubit.

Computes the real or imaginary part of the quantity \(\langle \partial_i \psi | \partial_j \psi \rangle\). See https://journals.aps.org/prx/abstract/10.1103/PhysRevX.7.021050 and section III.B of https://journals.aps.org/pra/abstract/10.1103/PhysRevA.99.032331.

Input state \(|\psi(\theta)\rangle\) is “regularized” so that all parameters are replaced with dummy parameters such that each gate in the state preparation circuit depends on a single dummy parameter, and each parameter appears only once: \(|\psi(\theta^{'})\rangle = \prod_i U_i(\theta_i^{'}) |0\rangle\). Using the chain rule, the derivative overlap is then given by \(\langle \partial_i \psi | \partial_j \psi \rangle = \sum_{kl} J_{ki} J_{lj} \langle \partial_k^{'} \psi | \partial_l^{'} \psi \rangle\) where \(J_{ki} = \partial\theta_k^{'}/\partial\theta_i\) is the Jacobian, and \(\langle \partial_k^{'} \psi | \partial_l^{'} \psi \rangle\) is the regularized derivative overlap, for which we construct circuits to compute.

Note

Imaginary part is not yet supported.

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

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

TOLERANCE = 1e-08
build(parameters, state, diff_symbols=None, component=NumberType.REAL, optimisation_level=1)

Build measurement circuits for a derivative overlap, or matrix of derivative overlaps (“Metric tensor”).

Parameters:
  • parameters (Union[SymbolDict, Dict]) – Numeric values for ansatz parameters.

  • state (GeneralAnsatz) – Parametrized input state \(|\psi(\theta)\rangle\) with which to calculate derivative overlap.

  • diff_symbols (Union[Tuple[Symbol, Symbol], List[Tuple[Symbol, Symbol]], None], default: None) – Symbol pairs with respect to which the bra and ket derivatives are computed. If None, the entire metric tensor is computed.

  • component (Union[str, NumberType], default: <NumberType.REAL: 'real'>) – Component of derivative overlap to measure: 'real' or 'imag'.

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

Note

Imaginary part is not yet supported.

Returns:

HadamardTestDerivativeOverlap – 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 calls the build() method for leaves of type MetricTensorReal.

Parameters:
Returns:

HadamardTestDerivativeOverlap – Returns the modified instance after building.

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:

HadamardTestDerivativeOverlap – 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.

distributions: Optional[List[EmpiricalDistribution]]
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_derivative_overlap()

Evaluates the derivative overlap, or matrix of derivative overlaps (“Metric tensor”).

Computes the derivative overlap for which this protocol was built.

Returns:

Dict[Tuple[Symbol, Symbol], float] – Dict of metric tensor elements indexed by the symbols with respect to which the bra and ket derivatives are performed.

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_dataframe_derivative_overlap()

Return pandas dataframe showing computational details.

Shows all ingredients in the calculation of the derivative overlap. Each row is a term in (the real or imaginary part of): \(\langle \partial_i \psi | \partial_j \psi \rangle = \sum_{kl} J_{ki} J_{lj} \langle \partial_k^{'} \psi | \partial_l^{'} \psi \rangle\).

Column headings are:
  • symbols: tuple of symbols i and j.

  • regularized symbols: tuple of symbols k and l.

  • prefactor: Product of Jacobians \(J_{ki} J_{lj}\). With a minus sign if necessary for the imaginary part.

  • circuit index: Index of measurement circuit in get_circuits() which computes the real/imag part of the regularized derivative overlap \(\langle \partial_k^{'} \psi | \partial_l^{'} \psi \rangle\). If None, the regularized derivative overlap is 1.

Returns:

DataFrame – Dataframe detailing the calculation.

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 evaluates quantum computables. If a computable is supported by this protocol, it is computed; otherwise, it returns the computable itself.

get_runner(qc)

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 MetricTensorReal.

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.

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 – 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.

parameters: Optional[SymbolDict]
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:

HadamardTestDerivativeOverlap – 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 HadamardTestDerivative(backend, shots_per_circuit=8000, direct=True)

Bases: LaunchRetrieveMixin, GenerateCircuitShotMixin, BuildClearMixin, ComputableCompliantMixin

Calculates a partial derivative of an expectation value using Hadamard test.

Implements the procedure and it’s variant described in arXiv:1701.01450.

If direct=True, both ancilla and all other qubits are measured (original method). If it is instead set to False, an alternative circuit is built, and only ancilla qubit is measured.

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

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

  • direct (bool, default: True) – Switching between direct- or indirect-type circuits.

build(parameters, state, operator, symbols, complex_part, optimisation_level=1)

Build the necessary circuits and measurement data for evaluating derivatives.

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

  • state (GeneralAnsatz) – Parametrized input state with which to calculate derivative.

  • operator (QubitOperator) – Operator kernel.

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed. If None, derivatives are computed with respect to all symbols.

  • complex_part (Union[ComplexPart, str]) – Component of derivative to measure, real or imaginary. Accepts strings 'real' and 'imag'.

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

Returns:

HadamardTestDerivative – 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 calls build for leaves of type:

Parameters:
Returns:

HadamardTestDerivative – Returns the modified instance after building.

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:

HadamardTestDerivative – 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_dbra(state, kernel, symbols, complex_part)

Evaluates partial bra derivatives of expectation value of a Hermitian operator.

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

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

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

  • symbols (Optional[Set[Symbol]]) – The set of symbols with respect to which the derivative will be evaluated. If None, the derivative will be evaluated with respect to all symbols found in the expressions.

  • complex_part (Union[ComplexPart, str]) – Component of the dbra expression to evaluate, real or imaginary, assuming the kernel is Hermitian. Accepts strings 'real' and 'imag'.

Returns:

Dict[Symbol, float] – A dictionary mapping each symbol to its corresponding derivative.

evaluate_dket(state, kernel, symbols, complex_part)

Evaluates partial ket derivatives of expectation value of a Hermitian operator.

If no symbols are provided, it will evaluate the derivative with respect to all symbols found in the state.

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

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

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

  • symbols (Optional[Set[Symbol]]) – The set of symbols with respect to which the derivative will be evaluated. If None, the derivative will be evaluated with respect to all symbols found in the expressions.

  • complex_part (Union[ComplexPart, str]) – Component of the dket expression to evaluate, real or imaginary, assuming the kernel is Hermitian. Accepts strings 'real' and 'imag'.

Returns:

Dict[Symbol, float] – A dictionary mapping each symbol to its corresponding derivative.

evaluate_gradient(state, kernel, symbols=None)

Evaluates gradient of expectation value of a Hermitian operator.

Since the kernel is Hermitian, the gradient is calculated as 2*Re(<dPsi|H|Psi>).

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

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

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

  • symbols (Optional[Set[Symbol]], default: None) – The set of symbols with respect to which the derivative will be evaluated. If None, the derivative will be evaluated with respect to all symbols found in the expressions.

Returns:

Dict[Symbol, float] – A dictionary mapping each symbol to its corresponding derivative.

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]], float] – 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 – 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.

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:

HadamardTestDerivative – 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 PhaseShift(backend, shots_per_circuit=8000, pauli_partition_strategy=PauliPartitionStrat.CommutingSets)

Bases: LaunchRetrieveMixin, GenerateCircuitShotMixin, BuildClearMixin, ComputableCompliantMixin

Calculates total gradient of an expectation value using gate parameter shift.

Implements the parameter-shift rule described in arXiv:1811.11184.

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

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

  • pauli_partition_strategy (PauliPartitionStrat, default: PauliPartitionStrat.CommutingSets) – Strategy to partition Pauli operators. Default is CommutingSets.

build(parameters, state, kernel, symbols=None, optimisation_level=1)

Build the necessary circuits and measurement data for evaluating derivatives.

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

  • state (GeneralAnsatz) – Parametrized input state with which to calculate derivative.

  • kernel (QubitOperator) – Operator kernel.

  • symbols (Optional[Set[Symbol]], default: None) – Symbols with respect to which the derivatives are computed. If None, derivatives are computed with respect to all symbols.

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

Returns:

PhaseShift – 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 calls build for leaves of type:

Parameters:
Returns:

PhaseShift – Returns the modified instance after building.

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:

PhaseShift – 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_dbra(state, kernel, symbols)

Evaluates partial bra derivatives of expectation value of a Hermitian operator.

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

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

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

  • symbols (Optional[Set[Symbol]]) – The set of symbols with respect to which the derivative will be evaluated. If None, the derivative will be evaluated with respect to all symbols found in the expressions.

Returns:

Dict[Symbol, float] – A dictionary mapping each symbol to its corresponding derivative.

evaluate_dket(state, kernel, symbols)

Evaluates partial ket derivatives of expectation value of a Hermitian operator.

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

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

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

  • symbols (Optional[Set[Symbol]]) – The set of symbols with respect to which the derivative will be evaluated. If None, the derivative will be evaluated with respect to all symbols found in the expressions.

Returns:

Dict[Symbol, float] – A dictionary mapping each symbol to its corresponding derivative.

evaluate_gradient(state, kernel, symbols=None)

Evaluates gradient of the expectation value of a Hermitian operator.

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

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

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

  • symbols (Optional[Set[Symbol]], default: None) – The set of symbols with respect to which the derivative will be evaluated. If None, the derivative will be evaluated with respect to all symbols found in the expressions.

Returns:

Dict[Symbol, float] – A dictionary mapping each symbol to its corresponding derivative.

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.

  • args (Any)

  • kwargs (Any)

Returns:

Callable[[Union[SymbolDict, Dict]], float] – 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:

PhaseShift – 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 Phase-Estimation

class CanonicalPhaseEstimation(backend, n_rounds, n_shots=10, compiler_passes=None, seed=None, optimisation_level=2)

Bases: DeterministicQPECircuitProtocol

Protocol for the generation of canonical Quantum Phase Estimation circuits.

Parameters:
  • backend (Backend) – pytket Backend object.

  • n_rounds (int) – Number of qubits in the readout register.

  • n_shots (int, default: 10) – Number of shots.

  • compiler_passes (Optional[BasePass], default: None) – Compiler passes to be used.

  • seed (Optional[int], default: None) – Random seed.

  • optimisation_level (int, default: 2) – Level of circuit optimization.

copy()

Returns a deep copy of the protocol.

Return type:

Protocol

class IterativePhaseEstimationSingleCircuit(backend, n_rounds, n_shots=10, compiler_passes=None, seed=None, optimisation_level=2)

Bases: DeterministicQPECircuitProtocol

Protocol for the generation of “one-circuit” iterative Quantum Phase Estimation circuits.

“One-circuit” here refers to the method of circuit generation, wherein the entire iterative phase estimation procedure is returned as a single circuit with extensive classical control. The successive rounds of phase estimation are concatenated into a single circuit, with the “correction” Z rotation generated by 2^N rotation gates, each classically controlled on the outcome of the preceding rounds of phase estimation.

Parameters:
  • backend (Backend) – pytket Backend object.

  • n_rounds (int) – Number of qubits in the readout register.

  • n_shots (int, default: 10) – Number of shots.

  • compiler_passes (Optional[BasePass], default: None) – Compiler passes to be used.

  • seed (Optional[int], default: None) – Random seed.

  • optimisation_level (int, default: 2) – Level of circuit optimization.

copy()

Returns a deep copy of the protocol.

Return type:

Protocol

class MeasurementPluralityPhaseEstimator

Bases: ShotBasedPhaseEstimator

Converts raw experimental results from a shot-based simulation to a phase, by taking the most frequent outcome.

class LinearInterpolatorPhaseEstimator

Bases: ShotBasedPhaseEstimator

Converts raw experimental results from a shot-based simulation to a phase, by generating a probability distribution function over the results.

The probability distribution function will be generated through periodic linear interpolation on the experimental results. Protocol execution will return an expected value of the phase by querying the PDF at every possible measurement outcome, and selecting the outcome with the highest probability.

class IterativePhaseEstimation(backend, n_shots=1, compilation_level=CompilationLevel.COMPILED, optimisation_level=1)

Bases: BaseIterativePhaseEstimationCircuit

Perform iterative QPE with a circuit with \(k\) and \(\beta\) to obtain the measurement outcome \(m\).

Parameters:
  • backend (Backend) – pytket backend.

  • n_shots (int, default: 1) – Number of shots (default: 1).

  • compilation_level (CompilationLevel, default: CompilationLevel.COMPILED) – Compilation level.

  • optimisation_level (int, default: 1) – Optimization level.

property backend: Backend | None

Backend object to be internally used.

property beta_iqpe: float

Circuit parameter \(\beta\).

build(state, evolution_operator_exponents, eoe_totally_commuting=None, ctrlu_strat=None, passes=None)

Build a function to generate Iterative QPE circuit using the Lie-Trotter product formula.

Parameters:
  • state (GeneralAnsatz) – Ansatz for the state preparation (non-symbolic).

  • evolution_operator_exponents (QubitOperatorList) – List of Pauli strings to be trotterized.

  • eoe_totally_commuting (Optional[QubitOperatorList], default: None) – Totally commuting set of Pauli strings to be added to the end of CTRL-U.

  • ctrlu_strat (Optional[CtrluStrat], default: None) – CTRL-U compilation strategy.

  • passes (Optional[BasePass], default: None) – Compiler pass to be applied for Ctrl-U circuit.

Returns:

BaseIterativePhaseEstimation – self

build_from_circuit(state, get_ctrlu)

Build the protocol using the lower-level inputs (circuits).

Parameters:
  • state (Circuit) – State preparation circuit.

  • get_ctrlu (Callable[[int], Circuit]) – Function to return a controlled unitary 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:

BaseIterativePhaseEstimationCircuit – self.

clear_cache()

Clear the circuit cache.

property compilation_level: CompilationLevel

Compilation level.

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.

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_distribuiton()

Get the distribution based on the measurement outcome.

Returns:

Mapping[Tuple[int, ...], float] – Distribution.

property get_iqpe_circuit: Callable[[int, float], Circuit]

Interface to the function to generate the IQPE circuit.

Returns:

function to build an IQPE circuit.

get_measurement_outcome()

Get the measurement outcome as a bit string.

Returns:

list[int] – List of int in {0, 1} to be used by iterative QPE algorithms.

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.

property k_iqpe: int

Circuit parameter \(k\).

launch(**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 (Mapping[str, 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.

property n_shots: int

Number of shots.

property optimisation_level: int

Optimization level.

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 (Mapping[str, Any]) – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

BaseIterativePhaseEstimation – 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.

update_k_and_beta(k, beta)

Update the circuit parameters k and beta.

Parameters:
  • k (int) – The number of repeats of the controlled unitary.

  • beta (float) – Pre-measurement rotation angle of ancilla.

Return type:

BaseIterativePhaseEstimationCircuit

class IterativePhaseEstimationQuantinuum(backend, n_shots=1, compilation_level=CompilationLevelQuantinuum.COMPILED, optimisation_level=1)

Bases: BaseIterativePhaseEstimationCircuit

General interface to the iterative QPE circuit with \(k\) and \(\beta\) to obtain the measurement outcome \(m\).

Parameters:
  • backend (Backend) – pytket backend.

  • n_shots (Union[int, Callable[[int], int]], default: 1) – Number of shots (default: 1).

  • compilation_level (CompilationLevelQuantinuum, default: CompilationLevelQuantinuum.COMPILED) – Compilation level.

  • optimisation_level (int, default: 1) – Optimization level.

Notes

If n_shots is given as a function, it takes \(k\) to dynamically set the number of shots.

property backend: Backend | None

Backend object to be internally used.

property beta_iqpe: float

Circuit parameter \(\beta\).

build(state, evolution_operator_exponents, encoding_method, encoding_options=None, eoe_totally_commuting=None, terms_map=None, paulis_map=None, time_split=None, ctrlu_strat=CtrluStrat.PAULI_EXP_BOX)

Build the controlled unitary function.

Parameters:
  • state (GeneralAnsatz) – Ansatz for the state preparation (non-symbolic).

  • evolution_operator_exponents (QubitOperatorList) – List of Pauli strings to be trotterized.

  • encoding_method (CircuitEncoderQuantinuum) – Encoding method of the logical qubit implementation.

  • encoding_options (Union[PlainOptions, IcebergOptions, None], default: None) – Encoding options of the logical qubit implementation.

  • eoe_totally_commuting (Optional[QubitOperatorList], default: None) – Totally commuting set of Pauli strings.

  • terms_map (Optional[Mapping[QubitPauliString, QubitPauliString]], default: None) – Pauli term mapping used when the Trotterization.

  • paulis_map (Optional[Mapping[QubitPauliString, QubitPauliString]], default: None) – Pauli term mapping for the optimization with the dummy qubit.

  • time_split (Optional[list[float]], default: None) – Delta t splitting for the gate error suppression.

  • ctrlu_strat (CtrluStrat, default: <CtrluStrat.PAULI_EXP_BOX: 0>) – Ctrl-U compilation strategy.

Return type:

IterativePhaseEstimationQuantinuum

build_from_circuit(state, get_ctrlu, encoding_method, encoding_options=None, get_ctrlu_totally_commuting=None)

Build the protocol using the lower-level inputs (circuits).

Parameters:
  • state (Circuit) – State preparation circuit.

  • get_ctrlu (Callable[[int], Circuit]) – Function to return a controlled unitary circuit.

  • encoding_method (CircuitEncoderQuantinuum) – Encoding method of the logical qubit implementation.

  • encoding_options (Union[PlainOptions, IcebergOptions, None], default: None) – Encoding options of the logical qubit implementation.

  • get_ctrlu_totally_commuting (Optional[Callable[[int], Circuit]], default: None) – Function to return a controlled unitary circuit (totally commuting set)

Return type:

IterativePhaseEstimationQuantinuum

Notes

get_ctrlu_totally_commuting is the IcebergCode only.

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:

BaseIterativePhaseEstimationCircuit – self.

clear_cache()

Clear the circuit cache.

property compilation_level: CompilationLevel

Compilation level.

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.

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_distribuiton()

Get the distribution based on the measurement outcome.

Returns:

Mapping[Tuple[int, ...], float] – Distribution.

property get_iqpe_circuit: Callable[[int, float], Circuit]

Interface to the function to generate the IQPE circuit.

Returns:

function to build an IQPE circuit.

get_measurement_outcome()

Get the measurement outcome as a bit string.

Returns:

list[int] – List of int in {0, 1} to be used by iterative QPE algorithms.

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.

property k_iqpe: int

Circuit parameter \(k\).

launch(**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 (Mapping[str, 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.

property n_shots: int

Number of shots.

property optimisation_level: int

Optimization level.

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 (Mapping[str, Any]) – Additional keyword arguments to be passed to self.backend.get_results() when retrieving results.

Returns:

IterativePhaseEstimationQuantinuum – 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.

update_k_and_beta(k, beta)

Update the circuit parameters k and beta.

Parameters:
  • k (int) – The number of repeats of the controlled unitary.

  • beta (float) – Pre-measurement rotation angle of ancilla.

Return type:

BaseIterativePhaseEstimationCircuit

class IterativePhaseEstimationStatevector(state_backend=None, unitary_backend=None, n_shots=1)

Bases: BaseIterativePhaseEstimation

Iterative phase estimation using the likelihood calculated with statevector simulation.

This class is designed for prototyping iterative QPE algorithms, rather than performing the production runs. The n_shots is recognized as a number of samples taken from the exact likelihood.

The exact likelihood is internally constructed by diagonalizing the unitary and the state population is calculated using the state preparation circuit. The get_distribution() returns exact distribution, rather than that from the measurement outcome.

Parameters:
  • state_backend (Optional[Backend], default: None) – pytket backend supporting get_state().

  • unitary_backend (Optional[Backend], default: None) – pytket backend supporting get_unitary().

  • n_shots (int, default: 1) – Number of shots (default: 1).

Note

Currently, state_backend=None and unitary_backend=None are required. External backends are not supported as for now, but the built-in functions of pytket.Circuit are used instead.

build(state, evolution_operator_exponents, eoe_totally_commuting=None)

Build the internal objects needed for the exact likelihood.

It calculate the eigenvalues and their populations in the initial state by the exact diagonalization of the Hamiltonian.

Parameters:
  • state (GeneralAnsatz) – Ansatz for state preparation (non-symbolic).

  • evolution_operator_exponents (QubitOperatorList) – List of Pauli strings to be trotterized.

  • eoe_totally_commuting (Optional[QubitOperatorList], default: None) – Totally commuting set of Pauli strings.

Returns:

IterativePhaseEstimationStatevector – Self.

build_from_circuit(state, get_ctrlu)

Build the protocol using the lower-level inputs (circuits).

Parameters:
  • state (Circuit) – State preparation circuit.

  • get_ctrlu (Callable[[int], Circuit]) – Function to return a CTRL-U circuit.

Return type:

IterativePhaseEstimationStatevector

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:

IterativePhaseEstimationStatevector – self.

property eigenvalues: ndarray

Eigenvalues to be used for generating the likelihood.

Returns:

Eigenvalues of the unitary \(U = e^{-iHt}\).

get_distribuiton()

Get the distribution based on the measurement outcome.

Returns:

Mapping[Tuple[int, ...], float] – Distribution.

get_distribution()

Distribution of the measurement outcome to be used by the iterative phase estimation algorithms.

Returns:

Mapping[Tuple[int, ...], float] – Probability to measure “0” from the ancilla qubit.

Notes

It returns the exact distribution, rather than that calculated from the measurement outcome.

get_measurement_outcome()

Measurement outcome to be used by the iterative phase estimation algorithms.

Returns:

list[int] – List of 0 or 1 as a measurement outcome of the IQPE circuit.

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_run

Boolean flag indicating if the instance has been run.

Returns:

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

launch()

Calculate the mock measurement outcome for the current \(k\) and \(\beta\).

Return type:

int

property populations: ndarray

Eigenstate populations to be used for generating the likelihood.

Returns:

Eigenstate Populations.

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(handle)

Retrieve the measurement outcome to get ready for invoking get_measurement_outcome().

Parameters:

handle (int) – The ID returned from launch() method.

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.

update_k_and_beta(k, beta)

Update the circuit parameters k and beta.

Parameters:
  • k (int) – The number of repeats of the controlled unitary.

  • beta (float) – Pre-measurement rotation angle of ancilla.

Return type:

IterativePhaseEstimationStatevector

Other protocols

class ProjectiveMeasurements(backend, shots_per_circuit)

Bases: LaunchRetrieveMixin, BuildClearMixin, GenerateCircuitShotMixin, PartiallyPickleable

This protocol measures the probability amplitudes of the computational basis states.

Examples

>>> from pytket.extensions.qiskit import AerBackend
>>> backend = AerBackend()
>>> circuit = Circuit(3).H(0).H(1).H(2)
>>> protocol = ProjectiveMeasurements(backend, 10000).build({}, CircuitAnsatz(circuit)).run(seed=0)
>>> protocol.get_dominant_basis_states(2)
[((1, 0, 0), 1278), ((0, 0, 0), 1275)]
>>> protocol.get_zero_state_probability()
0.1275
>>> protocol.get_zero_state_uncertainty()
0.0033353223232545307
>>> protocol.get_dataframe_basis_states(8)
  Basis State  Probability  Uncertainty  Count
0         100       0.1278     0.003339   1278
1         000       0.1275     0.003335   1275
2         011       0.1266     0.003325   1266
3         110       0.1262     0.003321   1262
4         101       0.1254     0.003312   1254
5         111       0.1241     0.003297   1241
6         001       0.1223     0.003276   1223
7         010       0.1201     0.003251   1201
Parameters:
  • backend (Backend) – The quantum backend to be used for measurements.

  • shots_per_circuit (int) – The number of measurement shots.

build(parameters, state, optimisation_level=1)

Builds the necessary circuits and measurement data for the state.

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

  • state (GeneralAnsatz) – The quantum state for which circuit is to be built.

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

Returns:

ProjectiveMeasurements – Self instance after building the necessary circuits and measurement data.

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:

ProjectiveMeasurements – self.

compile_circuits(optimisation_level=1)

Compiles circuits.

Parameters:

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

Returns:

ProjectiveMeasurements – Self instance after compiling circuits.

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.

counts: Optional[Counter]
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.

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_dataframe_basis_states(max_rows)

Get a DataFrame of basis states with probabilities and uncertainties.

Parameters:

max_rows (int) – The maximum number of rows to include in the DataFrame.

Returns:

A pandas DataFrame containing basis states, probabilities, uncertainties, and counts.

get_distribution()

Get the measurement distribution.

Returns:

Counter – The measurement distribution.

get_dominant_basis_states(n)

Get the n most dominant basis states and their counts.

Parameters:

n (int) – The number of dominant states to retrieve.

Returns:

List[Tuple[Tuple[int, ...], int]] – A list of tuples containing basis states and their corresponding counts.

get_phaseless_qubit_state(n)

Builds a qubit state with the n most common basis states.

The coefficients are set as the sqrt(probability), and the state will be normalized.

Note

This will not account for any phase the coefficients had originally.

Parameters:

n (int) – The number of most common basis states to include in the state.

Returns:

QubitState – The constructed qubit state.

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.

get_zero_state_probability()

Get the probability of measuring the zero state.

Returns:

float – The probability of measuring the zero state.

get_zero_state_uncertainty()

Get the uncertainty of the probability of measuring the zero state.

Returns:

float – The uncertainty of the probability of measuring the zero state.

property is_built: bool

Boolean flag indicating if the instance has been built.

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.

results: Optional[List[BackendResult]]
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:

ProjectiveMeasurements – 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 ProtocolList

Bases: LaunchRetrieveMixin, GenerateCircuitShotMixin

A class for containing multiple shot-based protocols.

This class combines multiple built protocols together to collectively manage their launch and retrieve workflow, and provide combined evaluator functions.

Note

The collection will only accept protocols that have been built (is_built == True).

Usage:
  • Instantiate backend, states and operator objects:

>>> from inquanto.protocols import ProtocolList, PauliAveraging, HadamardTestOverlap
>>> from pytket.extensions.qiskit import AerBackend
>>> backend = AerBackend()
>>> from pytket.circuit import Circuit
>>> from inquanto.ansatzes import CircuitAnsatz
>>> state1 = CircuitAnsatz(Circuit(4).X(0).X(1))
>>> state2 = CircuitAnsatz(Circuit(4).X(2).X(3))
>>> from inquanto.operators import QubitOperator
>>> op = QubitOperator("Y0 X1 X2 X3")
  • Create an instance of ProtocolList

>>> protocols = ProtocolList()
  • Create a protocol (assuming BuildClearMixin is the base protocol)

>>> protocol_pa = PauliAveraging(backend)
>>> protocol_ho = HadamardTestOverlap(backend, 1000)
  • Add the protocol to the protocol list

>>> protocols.append(protocol_pa.build({}, state1, op))
>>> protocols.append(protocol_ho.build({}, state1, state2, op, component="complex"))
  • Run the protocol list, which will run each protocol in the list.

>>> _ = protocols.run(seed=0)
  • Therefore the protocols in the list will have run status

>>> protocol_pa.is_run
True
>>> protocol_ho.is_run
True
  • Total circuit analysis:

>>> protocols.dataframe_circuit_shot()
    Qubits Depth Depth2q DepthCX  Shots
0        4     2       0       0   8000
1        5     8       4       4   1000
2        5     8       4       4   1000
Sum      -     -       -       -  10000
append(protocol)

Appends a built protocol to the collection.

Parameters:

protocol (BuildClearMixin) – The protocol to be appended.

Raises:

ValueError – If the protocol has not been built yet.

Return type:

None

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_protocol_circuit()

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

Returns:

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

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 quantum computable and evaluates it. The returned function iterates over the evaluators of constituent protocols. The input computable is evaluated by the first compatible evaluator.

Note

This evaluator works for quantum computables the protocols in the list have been built from.

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.

Returns:

Callable[[Evaluatable], Union[Evaluatable, Any]] – A function that can evaluate quantum computables.

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_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.

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:

ProtocolList – 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.

Error mitigation

class PMSV(stabilisers, atol=1e-10)

Bases: NoiseMitigation

Appends the physical symmetries of a system into the pauli-strings measured by a quantum circuit.

Implements the Partition Measurement Symmetry Verification error mitigation procedure described in arXiv:2109.08401

Shots are discarded when the parity of qubits which correspond to the measured Pauli words, does not match the expected parity given the symmetry of the provided QubitOperatorString objects.

Note

If measurement reduction is used in the protocol with strategy PauliPartitionStrat.NonConflicting, PMSV will overwrite the circuits with strategy PauliPartitionStrat.CommutingSets.

Parameters:
  • stabilisers (List[QubitOperator]) – List of state stabilizers as QubitOperator objects with only a single Pauli string in them.

  • atol (float, default: 1e-10) – Absolute tolerance for checking phase normalization of stabilizers.

post(backend_results, measurement_setup)

PMSV post method to modify backend results after measurements.

Parameters:
  • backend_results (List[BackendResult]) – The backend results to be modified.

  • measurement_setup (MeasurementSetup) – The measurement setup used for the measurements.

Returns:

Tuple[List[BackendResult], MeasurementSetup] – The modified backend results.

pre(state_circuit, measurement_circuits, measurement_setup)

PMSV pre method to modify measurement setup before measurements.

Parameters:
  • state_circuit (Circuit) – State preparation circuit.

  • measurement_circuits (List[Circuit]) – The measurement circuits for the measurements.

  • measurement_setup (MeasurementSetup) – The measurement setup to be modified.

Returns:

Tuple[Circuit, List[Circuit], MeasurementSetup] – The modified measurement setup.

class SPAM(backend, correlations=None)

Bases: NoiseMitigation

Interface to tket’s State Preparation And Measurement (SPAM) correction utility.

See pytket SPAM API reference

Parameters:
  • backend (Backend) – Backend to run calibration on.

  • correlations (Optional[List[List[Any]]], default: None) – The qubit_subsets parameter to be forwarded to SpamCorrecter in pytket.

calibrate(calibration_shots=50, **kwargs)

Generates the SPAM transition matrix by running tomography circuits.

Parameters:

calibration_shots (int, default: 50) – Number of calibration shots.

Returns:

SPAM – Self instance.

post(backend_results, measurement_setup)

SPAM post method to modify backend results after measurements.

Parameters:
  • backend_results (List[BackendResult]) – The backend results to be modified.

  • measurement_setup (MeasurementSetup) – The measurement setup used for the measurements.

Returns:

Tuple[List[BackendResult], MeasurementSetup] – The modified backend results.

pre(state_circuit, measurement_circuits, measurement_setup)

SPAM pre method to modify measurement setup before measurements.

Note

The method will compile circuits via a backend with optimisation level 1.

Parameters:
  • state_circuit (Circuit) – State preparation circuit.

  • measurement_circuits (List[Circuit]) – The measurement circuits for the measurements.

  • measurement_setup (MeasurementSetup) – The measurement setup to be modified.

Returns:

Tuple[Circuit, List[Circuit], MeasurementSetup] – The modified measurement setup.

class CombinedMitigation(mitms1, mitms2)

Bases: NoiseMitigation

A NoiseMitigation subclass to combine two NoiseMitigation objects.

This method allows you to compose two NoiseMitigation instances in such a way that the pre and post methods of the instances are called in sequence. The pre method of the second instance is called with the result of the pre method of the first instance, and the post method of the first instance is called with the result of the post method of the second instance.

That is (ms1 @ ms2).pre(...) is equivalent to ms2.pre(ms1.pre(...)) and (ms1 @ ms2).post(...) is equivalent to ms1.post(ms2.post(...)).

Parameters:
  • mitms1 (NoiseMitigation) – First NoiseMitigation object.

  • mitms2 (NoiseMitigation) – Second NoiseMitigation object.

post(backend_results, measurement_setup)

The post method to modify backend results after measurements.

This returns ms1.post(ms2.post(backend_results, measurement_setup)).

Parameters:
  • backend_results (List[BackendResult]) – The backend results to be modified.

  • measurement_setup (MeasurementSetup) – The measurement setup used for the measurements.

Returns:

Tuple[List[BackendResult], MeasurementSetup] – The modified backend results.

pre(state_circuit, measurement_circuits, measurement_setup)

The pre method to modify measurement setup before measurements.

This returns ms2.pre(ms1.pre(circuits, measurement_setup)).

Parameters:
  • state_circuit (Circuit) – State preparation circuit.

  • measurement_circuits (List[Circuit]) – The measurement circuits for the measurements.

  • measurement_setup (MeasurementSetup) – The measurement setup to be modified.

Returns:

Tuple[Circuit, List[Circuit], MeasurementSetup] – The modified measurement setup.

Utility classes

class ProtocolCache(level=CacheLevels.LIFETIME, max_mem_size=None, size_unit=CacheSizeUnit.MB, key_generator=None)

Bases: Cache

Specialises Cache to include protocol-specific functionality.

Parameters:
  • level (CacheLevels, default: CacheLevels.LIFETIME) – Cache level (CacheLevels.NONE: nothing is cached, or CacheLevels.LIFETIME: cache is not cleared during lifetime of the object, using it (unless memory used exceeds max_mem_size parameter value).

  • max_mem_size (Optional[int], default: None) – Maximum memory size that cache is allowed to occupy. Not checked if set to None.

  • size_unit (CacheSizeUnit, default: CacheSizeUnit.MB) – Memory size unit (used to process input and output).

  • key_generator (Optional[Callable[..., Hashable]], default: None) – Function to generate a key from the input objects.

Raises:

ValueError – When max_mem_size parameter has negative value.

property cache: Dict[Any, Any]

Returns the internal dict, storing cache.

property check_mem: bool

Returns whether the size of memory occupied by cache is to be checked at runtime.

Notes

Currently the Cache class does not check for memory size itself (except for the report). Such checks are supposed to be done by a handler (e.g. a caching decorator).

clear()

Clears cache.

Return type:

None

hashkey(*args, **kwargs)

Creates a hashable key from input arguments.

Overwrites same method from base class. Doesn’t use key_generator method that can be optionally passed as an argument to the base class constructor.

Parameters:
  • args (Any) – Arguments, to be made hashable.

  • kwargs (Any) – Keyword arguments, which values are to be made hashable.

Returns:

Tuple[Any, ...] – A list of hashable objects, to be used as a cache dict key.

Raises:

RuntimeError – If created key is not hashable.

property level: CacheLevels

Returns the cache level.

property max_mem_size: int | None

Returns the maximum allowed memory size for cache.

property mem_size: float

Calculates size of memory occupied by cache.

Currently uses implementation given here and converts result (in bytes) to the set memory size units.

property num_entries: int

Returns the number of entries currently stored in cache.

report()

Returns a pandas DataFrame object containing a report of the current state of cache.

Return type:

DataFrame

property size_unit: CacheSizeUnit

Returns the memory size unit as used by the class instance.

class PlainOptions(n_plus_states: int = 1)

Bases: NamedTuple

Plain code (physical qubit implementation) options for the IterativePhaseEstimationQuantinuum class.

Parameters:

n_plus_states – Number of \(|+\rangle\) states in the initial state.

n_plus_states: int

Alias for field number 0

class IcebergOptions(n_plus_states: int = 1, syndrome_interval: int = -1, sx_insertion: bool = False, conditional_exit: bool = False)

Bases: NamedTuple

Iceberg code options for the IterativePhaseEstimationQuantinuum class.

Parameters:
  • n_plus_states – Number of \(|+\rangle\) states in the initial state.

  • syndrome_interval – Syndrome measurement interval in the number of CTRL-U operations.

  • sx_insertion – X stabilizer insertion for the dynamical decoupling.

  • conditional_exit – Conditional exit (QuantinuumBackend only).

Notes

If the conditional_exit is used,

options = {
  'compiler_options': {
    'conditional_branching': True,
    'merge_classical_branches': True,
    'conditional_sq_gates': True
    }
}

must be passed to the QuantinuumBackend.process_circuit() function.

conditional_exit: bool

Alias for field number 3

n_plus_states: int

Alias for field number 0

sx_insertion: bool

Alias for field number 2

syndrome_interval: int

Alias for field number 1

class CircuitEncoderQuantinuum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Encoder options for the IterativePhaseEstimationQuantinuum class.

PLAIN

No logical qubit encoding to run physical qubit experiments.

ICEBERG

Apply \([[k+2, k, 2]]\) error detection code (dobbed Iceberg code).

ICEBERG = 1
PLAIN = 0
class CompilationLevel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: int, Enum

Compilation level used by IterativePhaseEstimation.

COMPILED is needed for a job to be run on a backend. The other options are used for analyzing the circuit.

LOGICAL

Flag to return the raw logical circuit.

COMPILED

Frag to return the compiled and optimized circuit for a given backend.

COMPILED = 0
LOGICAL = -1
as_integer_ratio()

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes(byteorder='big', *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class CtrluStrat(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: int, Enum

Enum of the strategy of CTRL-U compilation.

PAULI_EXP_BOX

Use PauliExpBox using CTRL-P(x) = ZP(-x/2)IP(x/2).

Pauli_GADGET_RZZ

Use Pauli gadgets but the CX Rz CX is replaced with Rzz.

PAULI_EXP_BOX = 0
PAULI_GADGET_RZZ = 1
as_integer_ratio()

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes(byteorder='big', *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.