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 orSymbolDict
containing the parameter values for the circuits.state (
GeneralAnsatz
) – Parametrized input state.operators (
QubitOperator
) – Qubit operators, the Pauli strings in theseQubitOperator
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’sget_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 thebuild()
method with the kernel operators associated with the state. It collects all created protocols into aProtocolList
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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
 dataframe_measurements()¶
Create a
DataFrame
consisting of computational details. Returns:
DataFrame
– A pandasDataFrame
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 pandasDataFrame
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.
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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 pytketResultHandle
objects representing the handles for the launched circuits.
 classmethod load(file, *args, **kwargs)¶
Load a pickled object from a file.
 Parameters:
 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:
 Returns:
TypeVar
(T
, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, *args, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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 theMitEx
instance. Step 3: Results are processed and internal data structures are updated. Parameters:
mitex (
MitEx
) – The instance ofMitEx
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 theMitRes
run is retrieved and internal data is updated. Parameters:
mitres (
MitRes
) – The instance ofMitRes
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 orSymbolDict
containing the parameter values for the circuits.state (
GeneralAnsatz
) – Parametrized input state.operators (
QubitOperator
) – Qubit operators, the Pauli strings in theseQubitOperator
objects are used to generate measurement circuits.optimisation_level (
int
, default:1
) – Passed to the backend’sget_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:
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.
 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 thebuild()
method with the kernel operators associated with the state. It collects all created protocols into aProtocolList
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
HadamardTest
.**kwargs – Keyword arguments passed to the constructor of
HadamardTest
.
 Returns:
ProtocolList
–ProtocolList
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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
 dataframe_measurements()¶
Create a
DataFrame
consisting of computational details. Returns:
DataFrame
– A pandasDataFrame
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.
 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:
state (
GeneralAnsatz
) – The quantum state for which the expectation value of the kernel is to be calculated.kernel (
Union
[QubitOperator
,QubitOperatorString
]) – 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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 pytketResultHandle
objects representing the handles for the launched circuits.
 classmethod load(file, *args, **kwargs)¶
Load a pickled object from a file.
 Parameters:
 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:
 Returns:
TypeVar
(T
, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, *args, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
Protocols for Overlap Squared¶
 class ComputeUncompute(backend, n_shots=8000)¶
Bases:
BaseOverlapSquaredProtocol
Calculates the overlap squared with the computeuncompute 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\psicP\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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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’sget_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 typeOverlapSquared
. 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.
 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 aProtocolList
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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
 dump(file)¶
Save the object to a file using pickle.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
Union
[QubitOperator
,QubitOperatorString
]) – Overlap kernel. Must be a single Pauli string.
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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 classmethod load(file, *args, **kwargs)¶
Load a pickled object from a file.
 Parameters:
 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:
 Returns:
TypeVar
(T
, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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\psicP\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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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’sget_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 typeOverlapSquared
. 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.
 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 aProtocolList
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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
 dump(file)¶
Save the object to a file using pickle.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
Union
[QubitOperator
,QubitOperatorString
]) – Overlap kernel. Must be a single Pauli string.
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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 classmethod load(file, *args, **kwargs)¶
Load a pickled object from a file.
 Parameters:
 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:
 Returns:
TypeVar
(T
, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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\psicP\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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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’sget_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 typeOverlapSquared
. 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.
 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 aProtocolList
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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
 dump(file)¶
Save the object to a file using pickle.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
Union
[QubitOperator
,QubitOperatorString
]) – Overlap kernel. Must be a single Pauli string.
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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 classmethod load(file, *args, **kwargs)¶
Load a pickled object from a file.
 Parameters:
 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:
 Returns:
TypeVar
(T
, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
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/13672630/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 nonidentity kernels. IfTrue
, 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
) – Fordirect=True
. Strategy to partition Pauli operators.pauli_colour_method (
Optional
[GraphColourMethod
], default:GraphColourMethod.Lazy
) – Fordirect=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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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
, orcomplex
.optimisation_level (
int
, default:1
) – Passed to the backend’sget_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 typeOverlap
,OverlapReal
, andOverlapImag
. Parameters:
 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 thebuild()
method with the kernel operators associated with the states. It collects all created protocols into aProtocolList
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
HadamardTestOverlap
.**kwargs – Keyword arguments passed to the constructor of
HadamardTestOverlap
.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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:
 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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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
, orcomplex
.optimisation_level (
int
, default:1
) – Passed to the backend’sget_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 typeOverlap
,OverlapReal
, andOverlapImag
. Parameters:
 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 thebuild()
method with the kernel operators associated with the states. It collects all created protocols into aProtocolList
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
HadamardTestOverlap
.**kwargs – Keyword arguments passed to the constructor of
HadamardTestOverlap
.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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 nonidentity kernels. IfTrue
, 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
) – Fordirect=True
. Strategy to partition Pauli operators.pauli_colour_method (
Optional
[GraphColourMethod
], default:GraphColourMethod.Lazy
) – Fordirect=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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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
, orcomplex
.optimisation_level (
int
, default:1
) – Passed to the backend’sget_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 typeOverlap
,OverlapReal
, andOverlapImag
. Parameters:
 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 thebuild()
method with the kernel operators associated with the states. It collects all created protocols into aProtocolList
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
HadamardTestOverlap
.**kwargs – Keyword arguments passed to the constructor of
HadamardTestOverlap
.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand 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
, orcomplex
.optimisation_level (
int
, default:1
) – Passed to the backend’sget_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 typeOverlap
,OverlapReal
, andOverlapImag
. Parameters:
 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 thebuild()
method with the kernel operators associated with the states. It collects all created protocols into aProtocolList
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
HadamardTestOverlap
.**kwargs – Keyword arguments passed to the constructor of
HadamardTestOverlap
.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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:
bra_state (
GeneralAnsatz
) – Lefthand state.ket_state (
GeneralAnsatz
) – Righthand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
StatevectorBased Protocols¶
 class SparseStatevectorProtocol(backend, cache=None, caching_decorator=cached)¶
Bases:
_BaseStatevectorProtocol
,EvaluatorRunnerMixin
Protocol for sparse statevector calculations using caching.
Uses an (optionally) externally provided cachehandling 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 cachehandling class object. IfNone
,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 cachehandler as parameters. By default, a function decorator local to the class module is used.
 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.
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 theComputable
is supported by this protocol, it is computed; otherwise, it returns theComputable
itself.
 get_runner(qc)¶
Returns an endtoend 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 afloat
, it returnsmath.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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 theComputable
is supported by this protocol, it is computed; otherwise, it returns theComputable
itself.
 get_runner(qc)¶
Returns an endtoend 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 afloat
, it returnsmath.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 isNone
.
 clear()¶
Resets the internal state of the object by clearing all stored data.
Clears runtime auxiliary variables in the protocol.
 Return type:
 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 theComputable
is supported by this protocol, it is computed; otherwise, it returns theComputable
itself.
 get_runner(qc)¶
Returns an endtoend 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 afloat
, it returnsmath.nan
.
Protocols for Derivatives¶
 class HadamardTestDerivativeOverlap(backend, shots_per_circuit=10000)¶
Bases:
ProtocolListItem
,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 = 1e08¶
 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. IfNone
, 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’sget_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 typeMetricTensorReal
. 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.
 Returns:
HadamardTestDerivativeOverlap
– Returns the modified instance after building.
 classmethod build_protocols_from(parameters, computable, exclude=None, optimisation_level=1, *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 state and calls the
build()
method. It collects all created protocols into aProtocolList
object to be returned. Parameters:
parameters (
Union
[dict
,SymbolDict
]) – 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.optimisation_level (
int
, default:1
) – Passed to the backend’sget_compiled_circuits()
method.*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.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
 dump(file)¶
Save the object to a file using pickle.
 dumps()¶
Returns the object pickled as a bytes object.
 Returns:
bytes
– The object’s state pickled as a bytes object.
 evaluate_derivative_overlap(state=None, diff_symbols=None)¶
Evaluates the derivative overlap, or matrix of derivative overlaps (“Metric tensor”).
If input args are code:None, computes the derivative overlap for which this protocol was built.
state: Quantum state for which the derivative overlap is to be calculated. diff_symbols: The set of symbols with respect to which the derivatives are evaluated. If
None
, allelements of the metric tensor are evaluated.
 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\). IfNone
, 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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 pytketResultHandle
objects representing the handles for the launched circuits.
 classmethod load(file, *args, **kwargs)¶
Load a pickled object from a file.
 Parameters:
 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:
 Returns:
TypeVar
(T
, bound= PartiallyPickleable) – An instance of the class with its state loaded from the pickled data.

parameters:
Optional
[SymbolDict
]¶
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, *args, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 class HadamardTestDerivative(backend, shots_per_circuit=8000, direct=True)¶
Bases:
ProtocolListItem
,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 toFalse
, an alternative circuit is built, and only ancilla qubit is measured. Parameters:
 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 orSymbolDict
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. IfNone
, 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’sget_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:
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.
 Returns:
HadamardTestDerivative
– Returns the modified instance after building.
 classmethod build_protocols_from(parameters, computable, exclude=None, optimisation_level=1, *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 state, component pair and calls the
build()
method. It collects all created protocols into aProtocolList
object to be returned. Parameters:
parameters (
Union
[dict
,SymbolDict
]) – 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.optimisation_level (
int
, default:1
) – Passed to the backend’sget_compiled_circuits()
method.*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.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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. IfNone
, 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. IfNone
, 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(<dPsiHPsi>).
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. IfNone
, 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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 pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, *args, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 class PhaseShift(backend, shots_per_circuit=8000, pauli_partition_strategy=PauliPartitionStrat.CommutingSets)¶
Bases:
ProtocolListItem
,ComputableCompliantMixin
Calculates total gradient of an expectation value using gate parameter shift.
Implements the parametershift 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 isCommutingSets
.
 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 orSymbolDict
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. IfNone
, derivatives are computed with respect to all symbols.optimisation_level (
int
, default:1
) – Passed to the backend’sget_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:
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.
 Returns:
PhaseShift
– Returns the modified instance after building.
 classmethod build_protocols_from(parameters, computable, exclude=None, optimisation_level=1, *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 state and calls the
build()
method. It collects all created protocols into aProtocolList
object to be returned. Parameters:
parameters (
Union
[dict
,SymbolDict
]) – 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.optimisation_level (
int
, default:1
) – Passed to the backend’sget_compiled_circuits()
method.*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.
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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. IfNone
, 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. IfNone
, 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. IfNone
, 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
) – IfFalse
, evaluation will fail when an unsupported computable node is encountered. IfTrue
, 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 endtoend 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
) – IfTrue
, circuits are immediately built and compiled symbolically. Calling the returned function substitutes symbols, runs circuits, and evaluates the output. IfFalse
, circuits are built and compiled only when the returned function is called and parameters are provided. Note that circuits may be deeper whencompile_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 afloat
, it returnsmath.nan
.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
Protocols for PhaseEstimation¶
 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:
 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 “onecircuit” iterative Quantum Phase Estimation circuits.
“Onecircuit” 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:
 copy()¶
Returns a deep copy of the protocol.
 Return type:
Protocol
 class MeasurementPluralityPhaseEstimator¶
Bases:
ShotBasedPhaseEstimator
Converts raw experimental results from a shotbased simulation to a phase, by taking the most frequent outcome.
 class LinearInterpolatorPhaseEstimator¶
Bases:
ShotBasedPhaseEstimator
Converts raw experimental results from a shotbased 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.
 build(state, evolution_operator_exponents, eoe_totally_commuting=None, ctrlu_strat=None, passes=None)¶
Build a function to generate Iterative QPE circuit using the LieTrotter product formula.
 Parameters:
state (
GeneralAnsatz
) – Ansatz for the state preparation (nonsymbolic).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 CTRLU.ctrlu_strat (
Optional
[CtrluStrat
], default:None
) – CTRLU compilation strategy.passes (
Optional
[BasePass
], default:None
) – Compiler pass to be applied for CtrlU circuit.
 Returns:
BaseIterativePhaseEstimation
– self
 build_from_circuit(state, get_ctrlu)¶
Build the protocol using the lowerlevel inputs (circuits).
 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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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.
 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.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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:
Notes
If
n_shots
is given as a function, it takes \(k\) to dynamically set the number of shots. 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 (nonsymbolic).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>
) – CtrlU compilation strategy.
 Return type:
 build_from_circuit(state, get_ctrlu, encoding_method, encoding_options=None, get_ctrlu_totally_commuting=None)¶
Build the protocol using the lowerlevel 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:
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.
 dataframe_circuit_shot()¶
Create a pandas
DataFrame
with circuit, shot, and depth information. Returns:
DataFrame
– A pandasDataFrame
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.
 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.
 get_shots()¶
Returns the number shots to be used for each circuit.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_numeric: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
False
if any built measurement circuit contains unsubstituted symbols, otherwiseTrue
.
 property is_run: bool¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 property is_symbolic: bool¶
Boolean flag indicating if the measurement circuits contain free symbols.
 Returns:
True
if any built measurement circuit contains unsubstituted symbols, otherwiseFalse
.
 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:
 Returns:
List
[ResultHandle
] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
 rebuild(*args, **kwargs)¶
Rebuild the internal data structure.
It is equivalent to
clear().build(*args, **kwargs)
.
 retrieve(source, **kwargs)¶
Retrieve distributions from the backend for the given source.
If the
source
is a list of pytketResultHandle
, the distributions are retrieved usingself.backend.get_results()
method. If thesource
is a list of pytketBackendResult
, it is assumed that the results are already provided. Parameters:
 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.
 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:
Note
Currently,
state_backend=None
andunitary_backend=None
are required. External backends are not supported as for now, but the builtin functions ofpytket.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 (nonsymbolic).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:
 build_from_circuit(state, get_ctrlu)¶
Build the protocol using the lowerlevel inputs (circuits).
 Parameters:
 Return type:
 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:
 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.
 get_distribution()¶
Distribution of the measurement outcome to be used by the iterative phase estimation algorithms.
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.
 property is_built: bool¶
Boolean flag indicating if the instance has been built.
 Returns:
True
if thebuild()
method has been successfully invoked, otherwiseFalse
.
 property is_run¶
Boolean flag indicating if the instance has been run.
 Returns:
True
if therun()
method has been successfully invoked, otherwiseFalse
.
 launch()¶
Calculate the mock measurement outcome for the current \(k\) and \(\beta\).
 Return type:
 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)
.
 retrieve(handle)¶
Retrieve the measurement outcome to get ready for invoking
get_measurement_outcome()
.
 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.
 update_k_and_beta(k, beta)¶
Update the circuit parameters k and beta.
 Parameters:
 Return type:
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 orSymbolDict
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’sget_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’sget_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.