inquanto.protocols¶
Protocols for Expectation Values¶
- class PauliAveraging(backend, shots_per_circuit=8000, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_color_method=GraphColourMethod.Lazy, **kwargs)¶
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 (Union[Backend, BackendConfig]) – 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_color_method (Optional[GraphColourMethod], default:
GraphColourMethod.Lazy
) – Method to perform graph coloring.**kwargs – Keyword arguments passed to the backend’s
get_compiled_circuits()
method.
- build(parameters, state, *operators, noise_mitigation=None)¶
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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – A dictionary 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.
- Returns:
PauliAveraging
– Self instance.
- build_from(parameters, computable, exclude=None, noise_mitigation=None)¶
Builds protocol circuits 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 circuit building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, noise_mitigation=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 internal state of the protocol.
- Return type:
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
PauliAveraging
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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'Standard error'
. 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'
,'Circuit index'
, and'Circuit 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_circuitshots()¶
Generates 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_evaluator_for_result(backend_result, *args, **kwargs)¶
Returns an evaluator function for a given backend result sampling.
Note
Internally, this creates a copy of the protocol.
- Parameters:
backend_result (
list
[BackendResult
]) – A pytketBackendResult
sampling.*args – Arguments to be passed to the
get_evaluator()
method.**kwargs – Keyword arguments to be passed to the
get_evaluator()
method.
- Returns:
Evaluatable
– A function that can evaluate quantum computable according toget_evaluator()
.
- get_evaluators_for_results(backend_result_sampling, *args, **kwargs)¶
Returns evaluator functions for a list of backend result samplings or a list of backend results.
This method creates sampled backend results and calls
get_evaluator()
using each of them.- Parameters:
backend_result_sampling (
Union
[BackendResultSampling
,list
[BackendResult
]]) – A pytketBackendResult
sampling method class or a list ofBackendResult
.*args – Arguments to be passed to the
get_evaluator()
method.**kwargs – Keyword arguments to be passed to the
get_evaluator()
method.
- Returns:
list
[Callable
[[Evaluatable
],Union
[Evaluatable
,Any
]]] – A list of functions that can evaluate quantum computables according toget_evaluator()
.
- get_runner(qc, compile_symbolic=False, *args, **kwargs)¶
Returns an end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],Any
] – A function that takes the parameters, builds and measures the necessary circuits, and returns the evaluated result.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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, **kwargs)¶
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 (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
shots_per_circuit (int, default:
8000
) – Number of shots for each circuit.**kwargs – Keyword arguments passed to the backend’s
get_compiled_circuits()
method.
- build(parameters, state, *operators)¶
Builds Hadamard test measurement circuits for each Pauli string.
Note
The coefficients in the operators are ignored.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – A dictionary 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.
- Returns:
TypeVar
(T
, bound= HadamardTest) – Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 circuit assembly.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a
ProtocolList
with circuits based on the given parameters and computable.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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
HadamardTest
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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'Standard error'
. 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_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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, **kwargs)¶
Bases:
BaseOverlapSquaredProtocol
Calculates the overlap squared with the compute-uncompute method.
For input states \(|{\psi}\rangle = U|{0}\rangle\) and \(|{\phi}\rangle = V|{0}\rangle\), prepares the state \(U^\dagger V|{0}\rangle\). The overlap squared \(|\langle{\psi|\phi}\rangle|^2\) is then given by the probability of measuring a vacuum state \(|{0}\rangle\). See https://arxiv.org/abs/1810.02327.
Supports calculation of overlap squared of the form: \(|\langle\psi|cP|\phi\rangle|^2\), where \(P\) is a Pauli word and \(c\) is a numeric constant.
- Parameters:
backend (Union[Backend, BackendConfig]) – 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)¶
Builds the necessary circuits and measurement data.
Note
Any coefficient in the operator kernel is ignored.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
Union
[QubitOperator
,QubitOperatorString
,None
], default:None
) – Optional operator kernel. Must be a single Pauli string.
- Returns:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol) – Self instance after building the necessary circuits and measurement data.
- build_from(parameters, computable, exclude=None, **kwargs)¶
Builds protocol circuits 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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.**kwargs (
Any
) – Keyword arguments to pass to thebuild()
method.
- Returns:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol) – Returns the modified instanceafter building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
- 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol)
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapSquaredProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
Note
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be
OverlapSquared
.Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
c (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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, **kwargs)¶
Bases:
BaseOverlapSquaredProtocol
Calculate the overlap squared with the destructive swap test.
Based on https://arxiv.org/abs/1303.6814. Prepares both bra and ket states in parallel and performs a destructive swap test i.e. no ancilla qubit is required. The test succeeds when a bitwise AND between the output bra and ket state registers has even parity. The probability of success is given by \(\frac{1}{2}(1+|\langle{\psi|\phi}\rangle|^2)\).
The bra state register is used as the control, while the ket register is the target.
Supports calculation of overlap squared of the form: \(|\langle\psi|cP|\phi\rangle|^2\), where \(P\) is a Pauli word and \(c\) is a numeric constant.
- Parameters:
backend (Union[Backend, BackendConfig]) – 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)¶
Builds the necessary circuits and measurement data.
Note
Any coefficient in the operator kernel is ignored.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
Union
[QubitOperator
,QubitOperatorString
,None
], default:None
) – Optional operator kernel. Must be a single Pauli string.
- Returns:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol) – Self instance after building the necessary circuits and measurement data.
- build_from(parameters, computable, exclude=None, **kwargs)¶
Builds protocol circuits 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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.**kwargs (
Any
) – Keyword arguments to pass to thebuild()
method.
- Returns:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol) – Returns the modified instanceafter building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
- 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol)
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapSquaredProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
Note
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be
OverlapSquared
.Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
c (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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, **kwargs)¶
Bases:
BaseOverlapSquaredProtocol
Calculate the overlap squared with the canonical swap test.
Input states \(|\psi\rangle\) and \(|\phi\rangle\) are prepared in parallel alongside an ancilla qubit to generate the state \(|0, \psi, \phi\rangle\). A swap operation between \(\psi\) and \(\phi\) is controlled on the ancilla and wrapped by Hadamard gates so that the probability of measuring \(|0\rangle\) on the ancilla is given by \(\frac{1}{2}(1+|\langle\psi|\phi\rangle|^2)\). See https://en.wikipedia.org/wiki/Swap_test.
Supports calculation of overlap squared of the form: \(|\langle\psi|cP|\phi\rangle|^2\), where \(P\) is a Pauli word and \(c\) is a numeric constant.
- Parameters:
backend (Union[Backend, BackendConfig]) – 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)¶
Builds the necessary circuits and measurement data.
Note
Any coefficient in the operator kernel is ignored.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
Union
[QubitOperator
,QubitOperatorString
,None
], default:None
) – Optional operator kernel. Must be a single Pauli string.
- Returns:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol) – Self instance after building the necessary circuits and measurement data.
- build_from(parameters, computable, exclude=None, **kwargs)¶
Builds protocol circuits 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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.**kwargs (
Any
) – Keyword arguments to pass to thebuild()
method.
- Returns:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol) – Returns the modified instanceafter building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
- 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
TypeVar
(T
, bound= BaseOverlapSquaredProtocol)
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapSquaredProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
Note
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be
OverlapSquared
.Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
c (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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=8000, direct=False, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_color_method=GraphColourMethod.Lazy, **kwargs)¶
Bases:
BaseOverlapProtocol
Calculates the overlap of two states using a specialized Hadamard test.
Computes the real or imaginary part of \(\langle A | B \rangle\) where \(|A\rangle = U_A |0\rangle\) using the “linear combination of unitaries” method from https://journals.aps.org/pra/abstract/10.1103/PhysRevA.99.032331 (see figure 2). For
direct=True
, this method uses the approach from https://iopscience.iop.org/article/10.1088/1367-2630/ab867b to combine ancilla and state register measurements to compute overlaps with kernels.- Parameters:
backend (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
shots_per_circuit (int, default:
8000
) – Number of shots to perform.direct (bool, default:
False
) – Relevant for overlaps with non-identity 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_color_method (Optional[GraphColourMethod], default:
GraphColourMethod.Lazy
) – Fordirect=True
. Method to perform graph coloring.
- build(parameters, bra_state, ket_state, *operators, component)¶
Builds the necessary circuits for computing an overlap.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Input bra state.state. (ket_state Input ket) –
*operators (
QubitOperator
) – Operator kernel.component (
Union
[str
,NumberType
]) – Component of overlap to compute.'real'
,'imag'
, or'complex'
.ket_state (
GeneralAnsatz
) –
- Returns:
BaseOverlapProtocol
– Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits 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:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameters for building.computable (
Any
) – A root node of a computable expression tree, simply it is a computable expression.exclude (
Optional
[Callable
[[Any
],bool
]], default:None
) – Optional callable function to exclude certain nodes from processing.
- Returns:
BaseOverlapProtocol
– The modified instance after building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
BaseOverlapProtocol
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
- Returns:
float
– Real part of the overlap.
- get_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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.**kwargs (
Any
) – Kwargs to be passed in to build the protocol.args (
Any
) –
- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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=8000, direct=False, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_color_method=GraphColourMethod.Lazy, **kwargs)¶
Bases:
BaseOverlapProtocol
Abstract base class for specialized overlap protocols between ansatzes that factorize into a reference and a number conserving unitary.
Computes the real or imaginary part of \(\langle A | B \rangle\) where \(|A\rangle = U_A U_\text{ref}|0\rangle\) and \(|B\rangle = U_B U_\text{ref}|0\rangle\) in the manner shown in Figures 1 and 2 of https://journals.aps.org/prxquantum/abstract/10.1103/PRXQuantum.4.030307. These protocols make use of the property that \(U_A |0\rangle = |0\rangle\) to avoid the potentially large controlled state unitaries involved in e.g.
HadamardTestOverlap
.Warning
Only ansatzes with the property that \(U_A |0\rangle = |0\rangle\) are compatible with protocols of this type.
- Parameters:
backend (Union[Backend, BackendConfig]) –
shots_per_circuit (int, default:
8000
) –direct (bool, default:
False
) –pauli_partition_strategy (Optional[PauliPartitionStrat], default:
PauliPartitionStrat.NonConflictingSets
) –pauli_color_method (Optional[GraphColourMethod], default:
GraphColourMethod.Lazy
) –
- build(parameters, bra_state, ket_state, *operators, component)¶
Builds the necessary circuits for computing an overlap.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Input bra state.state. (ket_state Input ket) –
*operators (
QubitOperator
) – Operator kernel.component (
Union
[str
,NumberType
]) – Component of overlap to compute.'real'
,'imag'
, or'complex'
.ket_state (
GeneralAnsatz
) –
- Returns:
BaseOverlapProtocol
– Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits 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:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameters for building.computable (
Any
) – A root node of a computable expression tree, simply it is a computable expression.exclude (
Optional
[Callable
[[Any
],bool
]], default:None
) – Optional callable function to exclude certain nodes from processing.
- Returns:
BaseOverlapProtocol
– The modified instance after building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
BaseOverlapProtocol
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
- Returns:
float
– Real part of the overlap.
- get_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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.**kwargs (
Any
) – Kwargs to be passed in to build the protocol.args (
Any
) –
- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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=8000, direct=False, pauli_partition_strategy=PauliPartitionStrat.NonConflictingSets, pauli_color_method=GraphColourMethod.Lazy, **kwargs)¶
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 (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
shots_per_circuit (int, default:
8000
) – Number of shots to perform.direct (bool, default:
False
) – Relevant for overlaps with non-identity 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_color_method (Optional[GraphColourMethod], default:
GraphColourMethod.Lazy
) – Fordirect=True
. Method to perform graph coloring.
- build(parameters, bra_state, ket_state, *operators, component)¶
Builds the necessary circuits for computing an overlap.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Input bra state.state. (ket_state Input ket) –
*operators (
QubitOperator
) – Operator kernel.component (
Union
[str
,NumberType
]) – Component of overlap to compute.'real'
,'imag'
, or'complex'
.ket_state (
GeneralAnsatz
) –
- Returns:
BaseOverlapProtocol
– Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits 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:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameters for building.computable (
Any
) – A root node of a computable expression tree, simply it is a computable expression.exclude (
Optional
[Callable
[[Any
],bool
]], default:None
) – Optional callable function to exclude certain nodes from processing.
- Returns:
BaseOverlapProtocol
– The modified instance after building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
BaseOverlapProtocol
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
- Returns:
float
– Real part of the overlap.
- get_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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.**kwargs (
Any
) – Kwargs to be passed in to build the protocol.args (
Any
) –
- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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=8000, **kwargs)¶
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 (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
shots_per_circuit (int, default:
8000
) – Number of shots to perform.**kwargs – Keyword arguments passed to the backend’s
get_compiled_circuits()
method.
- build(parameters, bra_state, ket_state, *operators, component)¶
Builds the necessary circuits for computing an overlap.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameter values for the circuits.bra_state (
GeneralAnsatz
) – Input bra state.state. (ket_state Input ket) –
*operators (
QubitOperator
) – Operator kernel.component (
Union
[str
,NumberType
]) – Component of overlap to compute.'real'
,'imag'
, or'complex'
.ket_state (
GeneralAnsatz
) –
- Returns:
BaseOverlapProtocol
– Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits 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:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Parameters for building.computable (
Any
) – A root node of a computable expression tree, simply it is a computable expression.exclude (
Optional
[Callable
[[Any
],bool
]], default:None
) – Optional callable function to exclude certain nodes from processing.
- Returns:
BaseOverlapProtocol
– The modified instance after building circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
BaseOverlapProtocol
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
BaseOverlapProtocol
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand 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
) – Left-hand state.ket_state (
GeneralAnsatz
) – Right-hand state.kernel (
QubitOperator
, default:{(): 1.0}
) – Operator kernel.
- Returns:
float
– Real part of the overlap.
- get_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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.**kwargs (
Any
) – Kwargs to be passed in to build the protocol.args (
Any
) –
- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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.
Statevector-Based Protocols¶
- class SparseStatevectorProtocol(backend, cache_dict=None, caching_decorator=cached, **kwargs)¶
Bases:
_BaseStatevectorProtocol
,PhaseShiftRuleMixin
Protocol for sparse statevector calculations using caching.
Uses an (optionally) externally provided cache-handling class and an external caching decorator to wrap its methods to be cached.
- Parameters:
backend (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
cache_dict (Optional[CacheDict], default:
None
) – A caching dict object. IfNone
, an emptyCacheDict
is implicitly instantiated.caching_decorator (Callable[[Callable[…, Any]], Callable[…, Any]], default:
cached
) – A caching decorator, that needs to take both an arbitrary function and a cache-handler as parameters. By default, a function decorator local to the class module is used.**kwargs (Any) – Keyword arguments passes to the backend.
- 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:
- 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. Supported computable are:
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.- Returns:
Callable
[[Union
[ndarray
,dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]]],Any
] – A function that takes the parameters and returns the evaluated result. If the result is not afloat
, it returnsmath.nan
.
- to_array(parameters)¶
Converts a dictionary of parameters to a numpy array.
- class BackendStatevectorProtocol(backend, *args, **kwargs)¶
Bases:
_BaseStatevectorProtocol
Statevector protocol utilizing backend functionality to enable statevector simulations.
- Parameters:
backend (Union[Backend, BackendConfig]) – 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:
- 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. Supported computables are:
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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:
StateBasedProtocolMixin
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:
- 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. Supported computables are:
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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, **kwargs)¶
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 (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
shots_per_circuit (int, default:
10000
) –Number of shots for each circuit.
**kwargs: Keyword arguments to be passed in to the backend.
- TOLERANCE = 1e-08¶
- build(parameters, state, diff_symbols=None, component=NumberType.REAL)¶
Builds measurement circuits for a derivative overlap, or matrix of derivative overlaps (“Metric tensor”).
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – Numeric values for ansatz parameters.state (
GeneralAnsatz
) – Parametrized input state \(|\psi(\theta)\rangle\) with which to calculate derivative overlap.diff_symbols (
Union
[tuple
[Symbol
,Symbol
],list
[tuple
[Symbol
,Symbol
]],None
], default:None
) – Symbol pairs with respect to which the bra and ket derivatives are computed. If None, the entire metric tensor is computed.component (
Union
[str
,NumberType
], default:<NumberType.REAL: 'real'>
) – Component of derivative overlap to measure: ‘real’ or ‘imag’.
Note
Imaginary part is not yet supported. A
DecomposeBoxes()
andDecomposeMultiQubitsCX()
pass will be applied to the state preparation circuits to reduce all parametrized gates to single qubit gates.- Returns:
HadamardTestDerivativeOverlap
– Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
- 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=None, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.“Preoptimization” passes, performed prior to the default optimization passes and any passes specified by
compiler_passes
, may optionally be specified via thepreoptimize_passes
argument. Default preoptimization passes are not available for this protocol, due to the passes applied during thebuild
stage – see documentation for thebuild()
method for further details.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Optional
[BasePass
], default:None
) – Preoptimize passes to be applied as above.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
HadamardTestDerivativeOverlap
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
- distributions: Optional[list[EmpiricalDistribution]]¶
- 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_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
Note
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be
MetricTensorReal
.Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.- Returns:
Callable
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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
.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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[dict[str | Symbol, CoeffType]]¶
- rebuild(*args, **kwargs)¶
Resets the internal state of the protocol, and rebuilds circuits.
- 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 wait 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, **kwargs)¶
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:
backend (Union[Backend, BackendConfig]) – The backend to use for quantum computations.
shots_per_circuit (int, default:
8000
) – Number of shots for each circuit.direct (bool, default:
True
) – Switching between direct- or indirect-type circuits.
- build(parameters, state, operator, symbols, component, optimisation_level=1)¶
Build the necessary circuits and measurement data for evaluating derivatives.
- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – A dictionary 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.component (
Union
[str
,NumberType
]) – Component of derivative to measure:'real'
,'imag'
or'complex'
.optimisation_level (
int
, default:1
) – Passed to the backend’sget_compiled_circuits()
method.
- Returns:
HadamardTestDerivative
– Self instance.
- build_from(parameters, computable, exclude=None)¶
Builds protocol circuits based on given parameters and computable expression.
This method walks over the computable expression tree and calls
build()
for leaves of type:- Parameters:
parameters (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 circuits.
- classmethod build_protocols_from(parameters, computable, exclude=None, *args, **kwargs)¶
Constructs a list of protocols with circuits based on the given parameters and computable.
- 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 (
dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]) – 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 protocols.
- clear()¶
Resets internal state of the protocol.
- Return type:
- compile_circuits(optimization_level=None, compiler_passes=None, preoptimize_passes=True, **kwargs)¶
Compiles circuits into a backend-specific form.
This uses the specified backend to compile circuits to a form suitable for running on the relevant machine. By default, compilation passes will be obtained by querying the backend. The choice of default compiler passes can be controlled with the
optimization_level
argument. If nocompiler_passes
argument is provided, this will default to 1.A custom set of compiler optimization passes can be provided through the
compiler_passes
argument. If this is provided,optimization_level
will default to 0 (no optimization). This can be overridden by explicitly specifying theoptimization_level
argument, whereupon the provided custom compiler passes will be performed after the requested default passes.By default, this will initially perform certain “preoptimization” passes where such are recommended by problem settings (for instance, by ansatz classes). This is performed prior to the default optimization passes and any passes specified by
compiler_passes
. This behavior can be disabled by settingpreoptimize_passes
toFalse
. This argument also can take a custom set of passes which will be used as a preoptimize stage instead.- Parameters:
optimization_level (
Optional
[int
], default:None
) – The default optimization level passed to the backend for automatic compilation pass choice. This defaults to 1 where no custom compiler passes are provided, otherwise 0.compiler_passes (
Optional
[BasePass
], default:None
) – Custom compiler passes to be performed subsequent to default passes.preoptimize_passes (
Union
[bool
,BasePass
], default:True
) – Whether to perform preoptimize passes as described above. Set to False to disable, or explicitly specify passes to perform instead.**kwargs (
Any
) – Additional keyword arguments passed to backend.
- Returns:
HadamardTestDerivative
– Self, with compiled 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.
- 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(optypes=())¶
Create a pandas
DataFrame
with circuit, shot, and depth information.- Parameters:
optypes (
Iterable
[OpType
], default:()
) – Additional gates, defined by pytketOpType
, for which the dataframe will contain depth and count data.- Returns:
DataFrame
– A pandasDataFrame
containing the circuit, shot, and depth information.
- evaluate_dbra(state, kernel, symbols, component)¶
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 component 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.component (
Union
[NumberType
,str
]) – Component of derivative to measure:'real'
,'imag'
or'complex'
.
- Returns:
dict
[Symbol
,Union
[float
,complex
]] – A dictionary mapping each symbol to its corresponding derivative.
- evaluate_dket(state, kernel, symbols, component)¶
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 component 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.component (
Union
[str
,NumberType
]) – Component of derivative to measure:'real'
,'imag'
or'complex'
.
- Returns:
dict
[Symbol
,Union
[float
,complex
]] – A dictionary mapping each symbol to its corresponding derivative.
- evaluate_dket_complex(state, kernel, symbols)¶
Evaluates complex ket derivatives of expectation value of a Hermitian operator.
This method calls the
evaluate_dket
function to separately handle the real and imaginary parts of the derivatives, and then combines these parts into a complex derivative.If no symbols are provided, it will evaluate the derivative with respect to all symbols found in the state.
- 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
,complex
] – A dictionary mapping each symbol to its corresponding complex derivative.
- evaluate_gradient(state, kernel, symbols=None)¶
Evaluates gradient of expectation value of a Hermitian operator.
Since the kernel is Hermitian, the gradient is calculated as 2*Re(<dPsi|H|Psi>).
This method can only be performed if, prior to calling this method, the protocol has been built for the state, kernel (or other operators composed of the same Pauli strings), symbols and
NumberType.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_circuitshots()¶
Generates 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 end-to-end executor function for a quantum computable.
All nodes in the quantum computable must be evaluable by this protocol. That is, the leaf nodes need to be of one of the supported types:
Note
At every call of the returned function the internal state of the protocol changes.
- Parameters:
qc (
ComputableNode
) – The quantum computable node to be measured and evaluated at every call of the returned function.compile_symbolic (
bool
, default:False
) – 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
[[dict
[str
|Symbol
,Union
[int
,float
,complex
,Expr
]]],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(n_circuits)¶
Returns the number of shots corresponding to each circuit.
- property is_compiled: bool¶
Boolean flag indicating if circuits have been compiled to the target backend.
- 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 protocol has run circuits and retrieved results from the backend.
- 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:
Union
[list
[ResultHandle
],tuple
[list
[ResultHandle
],list
[ResultHandle
]]] – A list of pytketResultHandle
objects representing the handles for the launched circuits.
- rebuild(*args, **kwargs)¶
Resets the internal state of the protocol, and rebuilds circuits.
- retrieve(*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 wait 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 Phase-Estimation¶
- class CanonicalPhaseEstimation(backend, n_rounds, n_shots=10, compiler_passes=None, seed=None, optimisation_level=2)¶
Bases:
DeterministicQPECircuitProtocol
Protocol for the generation of canonical Quantum Phase Estimation circuits.
- Parameters:
- copy()¶
Returns a deep copy of the protocol.
- Return type:
Protocol
- class IterativePhaseEstimationSingleCircuit(backend, n_rounds, n_shots=10, compiler_passes=None, seed=None, optimisation_level=2)¶
Bases:
DeterministicQPECircuitProtocol
Protocol for the generation of “one-circuit” iterative Quantum Phase Estimation circuits.
“One-circuit” here refers to the method of circuit generation, wherein the entire iterative phase estimation procedure is returned as a single circuit with extensive classical control. The successive rounds of phase estimation are concatenated into a single circuit, with the “correction” Z rotation generated by 2^N rotation gates, each classically controlled on the outcome of the preceding rounds of phase estimation.
- Parameters:
- copy()¶
Returns a deep copy of the protocol.
- Return type:
Protocol
- class MeasurementPluralityPhaseEstimator¶
Bases:
ShotBasedPhaseEstimator
Converts raw experimental results from a shot-based simulation to a phase, by taking the most frequent outcome.
- class LinearInterpolatorPhaseEstimator¶
Bases:
ShotBasedPhaseEstimator
Converts raw experimental results from a shot-based simulation to a phase, by generating a probability distribution function over the results.
The probability distribution function will be generated through periodic linear interpolation on the experimental results. Protocol execution will return an expected value of the phase by querying the PDF at every possible measurement outcome, and selecting the outcome with the highest probability.
- class IterativePhaseEstimation(backend=None, n_shots=1, compilation_level=CompilationLevel.COMPILED, optimisation_level=1, **kwargs)¶
Bases:
BaseIterativePhaseEstimationCircuit
Perform iterative QPE with a circuit with \(k\) and \(\beta\) to obtain the measurement outcome \(m\).
- Parameters:
backend (Optional[Union[Backend, BackendConfig]], default:
None
) –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 Lie-Trotter product formula.
- Parameters:
state (
GeneralAnsatz
) – Ansatz for the state preparation (non-symbolic).evolution_operator_exponents (
QubitOperatorList
) – List of Pauli strings to be trotterized.eoe_totally_commuting (
Optional
[QubitOperatorList
], default:None
) – Totally commuting set of Pauli strings to be added to the end of CTRL-U.ctrlu_strat (
Optional
[CtrluStrat
], default:None
) – CTRL-U compilation strategy.passes (
Optional
[BasePass
], default:None
) – Compiler pass to be applied for Ctrl-U circuit.
- Returns:
BaseIterativePhaseEstimation
– self
- build_from_circuit(state, get_ctrlu)¶
Build the protocol using the lower-level inputs (circuits).
- clear()¶
- Return type:
BaseIterativePhaseEstimationCircuit
- clear_cache()¶
Clear the circuit cache.
- property compilation_level: CompilationLevel¶
Compilation level.
- 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_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.
- 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_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.
- 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 wait 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 (non-symbolic).evolution_operator_exponents (
QubitOperatorList
) – List of Pauli strings to be trotterized.encoding_method (
CircuitEncoderQuantinuum
) – Encoding method of the logical qubit implementation.encoding_options (
Union
[PlainOptions
,IcebergOptions
,None
], default:None
) – Encoding options of the logical qubit implementation.eoe_totally_commuting (
Optional
[QubitOperatorList
], default:None
) – Totally commuting set of Pauli strings.terms_map (
Optional
[Mapping
[QubitPauliString
,QubitPauliString
]], default:None
) – Pauli term mapping used when the Trotterization.paulis_map (
Optional
[Mapping
[QubitPauliString
,QubitPauliString
]], default:None
) – Pauli term mapping for the optimization with the dummy qubit.time_split (
Optional
[list
[float
]], default:None
) – Delta t splitting for the gate error suppression.ctrlu_strat (
CtrluStrat
, default:<CtrluStrat.PAULI_EXP_BOX: 0>
) – Ctrl-U compilation strategy.
- Return type:
- build_from_circuit(state, get_ctrlu, encoding_method, encoding_options=None, get_ctrlu_totally_commuting=None)¶
Build the protocol using the lower-level inputs (circuits).
- Parameters:
state (
Circuit
) – State preparation circuit.get_ctrlu (
Callable
[[int
],Circuit
]) – Function to return a controlled unitary circuit.encoding_method (
CircuitEncoderQuantinuum
) – Encoding method of the logical qubit implementation.encoding_options (
Union
[PlainOptions
,IcebergOptions
,None
], default:None
) – Encoding options of the logical qubit implementation.get_ctrlu_totally_commuting (
Optional
[Callable
[[int
],Circuit
]], default:None
) – Function to return a controlled unitary circuit (totally commuting set)
- Return type:
Notes
get_ctrlu_totally_commuting
is the IcebergCode only.
- clear()¶
- Return type:
BaseIterativePhaseEstimationCircuit
- clear_cache()¶
Clear the circuit cache.
- property compilation_level: CompilationLevel¶
Compilation level.
- 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_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.
- 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_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.
- 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 wait 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:
state_backend (Optional[Union[Backend, BackendConfig]], default:
None
) –pytket
backend supportingget_state()
.unitary_backend (Optional[Union[Backend, BackendConfig]], default:
None
) –pytket
backend supportingget_unitary()
.n_shots (int, default:
1
) – Number of shots (default: 1).
Note
Currently,
state_backend=None
andunitary_backend=None
are required. External backends are not supported as for now, but the built-in 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 (non-symbolic).evolution_operator_exponents (
QubitOperatorList
) – List of Pauli strings to be trotterized.eoe_totally_commuting (
Optional
[QubitOperatorList
], default:None
) – Totally commuting set of Pauli strings.
- Returns:
- build_from_circuit(state, get_ctrlu)¶
Build the protocol using the lower-level inputs (circuits).
- Parameters:
- Return type:
- clear()¶
- Return type:
- 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