import inspect
from typing import get_args, get_origin, no_type_check, overload
from guppylang import array, comptime, guppy
from guppylang.defs import GuppyFunctionDefinition
from guppylang.std.debug import state_output
from guppylang.std.quantum import discard_array, qubit
from selene_sim.backends import Stim
from selene_sim.build import build
from selene_stim_plugin import SeleneStimState
from zixy.qubit import pauli
from guppyft.code_def import StabilizerCode, _identity_code
from guppyft.verify._adapters import _to_array
from guppyft.verify._expansion import get_expanded_stabilizer_set
from guppyft.verify._state_gen import gen_choi_state
from guppyft.verify._utils import (
ImplementationCliffordUnitary,
ImplementationCliffordUnitaryDouble,
ImplementationStabilizerState,
ImplementationStabilizerStateDouble,
SemanticCliffordUnitary,
SemanticCliffordUnitaryDouble,
SemanticStabilizerState,
SemanticStabilizerStateDouble,
stabilizerlist_to_signterms,
)
def _invoke_selene_stim(
main_function: GuppyFunctionDefinition[[], None],
num_selene_qubits: int,
seed: int = 123,
) -> dict[str, SeleneStimState]:
instance = build(main_function.compile())
seeded_stim_instance = Stim(random_seed=seed)
output = instance.run(simulator=seeded_stim_instance, n_qubits=num_selene_qubits)
return seeded_stim_instance.extract_states_dict(output)
_INNER_ARRAY_SIZE = guppy.type_var("_INNER_ARRAY_SIZE")
_N_ARRAYS = guppy.type_var("_N_ARRAYS")
def _compute_stabilisers(
qubit_prep_func: GuppyFunctionDefinition[
[], array[array[qubit, _INNER_ARRAY_SIZE], _N_ARRAYS] # type: ignore[valid-type]
],
*,
n_groups: int,
num_selene_qubits: int,
) -> pauli.SignTerms:
"""Compute the stabilizers of a range of qubits that is provided as an array of
arrays of qubits. The given arrays will be concatenated in the given order.
Args:
qubit_prep_func: A Guppy function that prepares all the qubit groups.
n_groups: Number of blocks prepared by the state preparation.
num_selene_qubits: An upper bound for the number of qubits used in
`groups_prep_func`.
Returns:
A Zixy `SignTerms` instance storing the stabilizers of the qubit groups.
"""
# Explicit parameters in generic comptime functions are not yet supported
@guppy
@no_type_check
def empty_qubit_array() -> array[qubit, 0]:
return array()
@guppy.comptime
@no_type_check
def main() -> None:
groups = qubit_prep_func()
for i in range(n_groups):
state_output(f"group_{i}", groups[i])
discard_array(groups[i])
# A hack to get a state_output over all groups together but avoid reforming them
# into a single array. Used in conjunction with modifying the specified qubits
# of the final simulation state below, which works because stabilizer extraction
# is delayed until the respective call.
qb_array = empty_qubit_array()
state_output("total", qb_array)
qb_array.discard_all_taken()
states_dict = _invoke_selene_stim(main, num_selene_qubits)
# See explanation above
total = states_dict["total"]
total.specified_qubits = [
q for i in range(n_groups) for q in states_dict[f"group_{i}"].specified_qubits
]
stab_list = states_dict["total"].get_reduced_stabilizers()
return stabilizerlist_to_signterms(stab_list)
def _compute_stabilizers_state[B](
code: StabilizerCode,
state_prep_func: GuppyFunctionDefinition[[], B],
*,
n_blocks: int,
num_selene_qubits: int,
) -> pauli.SignTerms:
"""Compute the stabilizers of a prepared state.
Args:
code: The stabilizer code.
state_prep_func: A Guppy function that prepares the stabilizer state on a single
code block.
n_blocks: Number of blocks prepared by the state preparation.
num_selene_qubits: An upper bound for the number of qubits used in
`state_prep_func`.
Returns:
A Zixy `SignTerms` instance storing the stabilizers of the prepared state.
"""
n = code.n_physical_qubits
# Workaround for https://github.com/Quantinuum/guppylang/issues/2597.
# TODO generalise and merge into a comptime function once the issue is fixed.
if n_blocks == 1:
@guppy
@no_type_check
def group_prep_func() -> array[array[qubit, n], n_blocks]:
return array(_to_array(state_prep_func()))
else:
@guppy
@no_type_check
def group_prep_func() -> array[array[qubit, n], n_blocks]:
first, second = state_prep_func()
return array(_to_array(first), _to_array(second))
return _compute_stabilisers(
group_prep_func, n_groups=n_blocks, num_selene_qubits=num_selene_qubits
)
def _compute_stabilizers_unitary[**B](
code: StabilizerCode,
clifford_func: GuppyFunctionDefinition[B, None],
*,
n_blocks: int,
num_selene_qubits: int,
) -> pauli.SignTerms:
"""Compute the stabilizers of a Choi state encoding a Clifford operation.
Args:
code: The stabilizer code.
clifford_func: A Guppy function which implements a Clifford unitary
on a single code block.
n_blocks: Number of blocks transformed by the unitary.
num_selene_qubits: An upper bound for the number of qubits used in the Choi
state for `clifford_func`.
Returns:
A Zixy `SignTerms` instance storing the stabilizers of the Choi state.
"""
choi_prep = gen_choi_state(code, clifford_func, n_blocks=n_blocks) # type: ignore[call-overload]
n = code.n_physical_qubits
@guppy
@no_type_check
def group_prep_func() -> array[array[qubit, n], comptime(2 * n_blocks)]:
return choi_prep[n]()
return _compute_stabilisers(
group_prep_func, n_groups=2 * n_blocks, num_selene_qubits=num_selene_qubits
)
def _count_blocks_state(
semantic_function: SemanticStabilizerState | SemanticStabilizerStateDouble,
impl_function: ImplementationStabilizerState | ImplementationStabilizerStateDouble,
) -> int:
sem_sig = inspect.signature(semantic_function.wrapped.python_func) # type: ignore[attr-defined]
impl_sig = inspect.signature(impl_function.wrapped.python_func) # type: ignore[attr-defined]
sem_return = sem_sig.return_annotation
impl_return = impl_sig.return_annotation
if (get_origin(sem_return) is tuple) ^ (get_origin(impl_return) is tuple):
raise TypeError(
"semantic_function and impl_function have incompatible signatures"
)
if get_origin(sem_return) is tuple:
return len(get_args(sem_return))
return 1
@overload
def _compute_state_prep_tableaux(
semantic_function: SemanticStabilizerState,
impl_function: ImplementationStabilizerState,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]: ...
@overload
def _compute_state_prep_tableaux(
semantic_function: SemanticStabilizerStateDouble,
impl_function: ImplementationStabilizerStateDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]: ...
def _compute_state_prep_tableaux(
semantic_function: SemanticStabilizerState | SemanticStabilizerStateDouble,
impl_function: ImplementationStabilizerState | ImplementationStabilizerStateDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]:
"""Compute tableaux pair for logical state prep on one or two blocks.
Given a semantic Guppy function acting on k qubits and an impl Guppy function
acting on n qubits, compute a pair of stabilizer tableaux. Note that we will need
to canonicalize with SignTerms.canonicalize_all() before we can check for equality.
Args:
semantic_function: A Guppy function for semantic action
of a Clifford operator on `k` logical qubits.
impl_function: A Guppy function for implementing the semantics on `n` physical
qubits.
code_definition: A stabilizer code with well-defined :math:`[[n, k, d]]`
parameters, stabilizer generators, and logical operators.
n_impl_ancillas: The number of ancilla qubits used in the implementation.
Defaults to None meaning that no ancilla qubits are used by default.
Returns:
A pair of stabilizer tableaux made up of signed Pauli terms.
"""
num_blocks = _count_blocks_state(semantic_function, impl_function)
if num_blocks not in (1, 2):
raise TypeError(
"Unsupported number of code block parameters in semantic_function."
+ f"Got {num_blocks} blocks. Only 1 and 2 are supported."
)
n_stab_qubits = num_blocks * code_definition.n_physical_qubits
if n_impl_ancillas is not None:
n_stab_qubits += n_impl_ancillas
# Get the k*num_blocks logical stabilizers for the logical state.
semantic_stabilizers = _compute_stabilizers_state(
_identity_code(code_definition.n_logical_qubits),
semantic_function,
n_blocks=num_blocks,
num_selene_qubits=num_blocks * code_definition.n_logical_qubits,
)
# Calculate the n*num_blocks physical stabilizers of the physical state.
implementation_stabilizers = _compute_stabilizers_state(
code_definition,
impl_function,
n_blocks=num_blocks,
num_selene_qubits=n_stab_qubits,
)
# Expand the num_blocks*k logical stabilizers to stabilizers of size num_blocks*n.
# We also add the num_blocks*(n-k) stabilizer generators of our code.
# We have num_blocks * k + num_blocks*(n-k) = num_blocks*n stabilizers in total.
expanded_semantic_stabilizers = get_expanded_stabilizer_set(
semantic_stabilizers, code_definition, num_blocks=num_blocks
)
return expanded_semantic_stabilizers, implementation_stabilizers
@overload
def valid_stabilizer_state_preparation(
semantic_function: SemanticStabilizerState,
impl_function: ImplementationStabilizerState,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> bool: ...
@overload
def valid_stabilizer_state_preparation(
semantic_function: SemanticStabilizerStateDouble,
impl_function: ImplementationStabilizerStateDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> bool: ...
[docs]
def valid_stabilizer_state_preparation(
semantic_function: SemanticStabilizerState | SemanticStabilizerStateDouble,
impl_function: ImplementationStabilizerState | ImplementationStabilizerStateDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> bool:
"""Checks whether `impl_function` is a valid implementation of `semantic_function`.
Validates the implementation of a logical state preparation function. The
program must contain only Clifford gates and measurements. The resulting
state may be on a single code block or entangle two code blocks.
Args:
semantic_function: A Guppy function for semantic action
of Pauli eigenstate preparation over one or two code blocks.
impl_function: A Guppy function for preparing the logical eigenstate
over one or two code blocks.
code_definition: A stabilizer code with well-defined :math:`[[n, k, d]]`
parameters, stabilizer generators, and logical operators.
n_impl_ancillas: The number of ancilla qubits used in the implementation.
Defaults to None meaning that no ancilla qubits are used by default.
Returns:
A Boolean indicating whether the state preparation is valid.
.. testcode::
from guppylang import guppy
from guppylang.std.builtins import array
from guppylang.std.quantum import cx, h, qubit
from guppyft.code_def import StabilizerCode
from guppyft.verify import valid_stabilizer_state_preparation
CSS_4Q_DEF = StabilizerCode.from_python_strings(
n_physical_qubits=4,
n_logical_qubits=2,
distance=2,
generators=["XXXX", "ZZZZ"],
x_logicals=["XXII", "XIXI"],
z_logicals=["IZIZ", "IIZZ"],
)
@guppy
def specify_zero_state() -> array[qubit, 2]:
return array(qubit() for _ in range(2))
@guppy
def implement_non_ft_zero_state() -> array[qubit, 4]:
block = array(qubit() for _ in range(4))
h(block[0])
cx(block[0], block[1])
cx(block[0], block[2])
cx(block[0], block[3])
return block
assert valid_stabilizer_state_preparation(
specify_zero_state,
implement_non_ft_zero_state,
CSS_4Q_DEF,
)
"""
sem_stabilizers, impl_stabilizers = _compute_state_prep_tableaux(
semantic_function, # type: ignore[arg-type]
impl_function, # type: ignore[arg-type]
code_definition,
n_impl_ancillas,
)
# Canonicalize both Clifford Tableaux so that we can test for equality.
sem_stabilizers.canonicalize_all()
impl_stabilizers.canonicalize_all()
return sem_stabilizers == impl_stabilizers
def _count_blocks_unitary(
semantic_function: SemanticCliffordUnitary | SemanticCliffordUnitaryDouble,
impl_function: ImplementationCliffordUnitary | ImplementationCliffordUnitaryDouble,
) -> int:
sem_signature = inspect.signature(semantic_function.wrapped.python_func) # type: ignore[attr-defined]
impl_signature = inspect.signature(impl_function.wrapped.python_func) # type: ignore[attr-defined]
if len(sem_signature.parameters) != len(impl_signature.parameters):
raise TypeError(
"semantic_function and impl_function have incompatible signatures"
)
return len(sem_signature.parameters)
@overload
def _compute_clifford_tableaux(
semantic_function: SemanticCliffordUnitary,
impl_function: ImplementationCliffordUnitary,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]: ...
@overload
def _compute_clifford_tableaux(
semantic_function: SemanticCliffordUnitaryDouble,
impl_function: ImplementationCliffordUnitaryDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]: ...
@overload
def _compute_clifford_tableaux(
semantic_function: SemanticCliffordUnitary | SemanticCliffordUnitaryDouble,
impl_function: ImplementationCliffordUnitary | ImplementationCliffordUnitaryDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]: ...
def _compute_clifford_tableaux(
semantic_function: SemanticCliffordUnitary | SemanticCliffordUnitaryDouble,
impl_function: ImplementationCliffordUnitary | ImplementationCliffordUnitaryDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> tuple[pauli.SignTerms, pauli.SignTerms]:
"""Compute a pair of tableaux for a logical Clifford on one or two blocks.
Given a semantic Guppy function acting on k qubits and an impl Guppy function
acting on n qubits, compute a pair of Clifford tableaux. Note that we will need to
canonicalize with SignTerms.canonicalize_all() before we can check for equality.
Args:
semantic_function: A Guppy function for semantic action
of a Clifford operator on :math:`k` logical qubits.
impl_function: A Guppy function for implementing
the semantics on `n` physical qubits.
code_definition: A stabilizer code with well-defined :math:`[[n, k, d]]`
parameters, stabilizer generators and logical operators.
n_impl_ancillas: The number of ancilla qubits used in the implementation.
Defaults to None meaning that no ancilla qubits are used by default.
Returns:
A pair of Clifford tableaux made up of signed Pauli terms.
"""
num_blocks = _count_blocks_unitary(semantic_function, impl_function)
n_physical_choi_qubits = 2 * num_blocks * code_definition.n_physical_qubits
if num_blocks not in (1, 2):
raise TypeError(
"Unsupported number of code block parameters in semantic_function."
+ f"Got {num_blocks} blocks. Only 1 and 2 are supported."
)
if n_impl_ancillas is not None:
n_physical_choi_qubits += n_impl_ancillas
# Get the 2*k*num_blocks stabilizers of the qubit Choi state encoding the logical.
semantic_choi_stabilizers = _compute_stabilizers_unitary(
_identity_code(code_definition.n_logical_qubits),
semantic_function,
n_blocks=num_blocks,
num_selene_qubits=num_blocks * 2 * code_definition.n_logical_qubits,
)
# Calculate the 2*n*num_blocks stabilizers of the Choi state encoding the physical.
implementation_stabilizers = _compute_stabilizers_unitary(
code_definition,
impl_function,
n_blocks=num_blocks,
num_selene_qubits=n_physical_choi_qubits,
)
# Expand 2*num_blocks*k logical stabilizers to stabilizers of size 2*num_blocks*n.
# We also add the 2*num_blocks(n-k) stabilizer generators of our code.
# For each code block there are 2(n-k) so we have 2*num_blocks*(n-k) in total.
# We have 2*num_blocks*k + 2*num_blocks*(n-k) = 2*num_blocks*n stabilizers in total.
expanded_semantic_stabilizers = get_expanded_stabilizer_set(
semantic_choi_stabilizers, code_definition, num_blocks=2 * num_blocks
)
return expanded_semantic_stabilizers, implementation_stabilizers
@overload
def valid_clifford_implementation(
semantic_function: SemanticCliffordUnitary,
impl_function: ImplementationCliffordUnitary,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> bool: ...
@overload
def valid_clifford_implementation(
semantic_function: SemanticCliffordUnitaryDouble,
impl_function: ImplementationCliffordUnitaryDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> bool: ...
[docs]
def valid_clifford_implementation(
semantic_function: SemanticCliffordUnitary | SemanticCliffordUnitaryDouble,
impl_function: ImplementationCliffordUnitary | ImplementationCliffordUnitaryDouble,
code_definition: StabilizerCode,
n_impl_ancillas: int | None = None,
) -> bool:
"""Checks whether `impl_function` is a valid implementation of `semantic_function`.
Validates the implementation of a Clifford function acting one or two code blocks.
Args:
semantic_function: A Guppy function for semantic action
of a Clifford operator on one or two code blocks.
impl_function: A Guppy function for implementing
the semantics on one or two code blocks.
code_definition: A stabilizer code with well defined :math:`[[n, k, d]]`
parameters, stabilizer generators and logical operators.
n_impl_ancillas: The number of ancilla qubits used in the implementation.
Defaults to None meaning that no ancilla qubits are used by default.
Returns:
A Boolean indicating whether the implementation is valid.
.. testcode::
from guppylang import guppy
from guppylang.std.builtins import array
from guppylang.std.quantum import qubit, h
from guppyft.code_def import StabilizerCode
from guppyft.verify import valid_clifford_implementation
STEANE_DEF = StabilizerCode.from_python_strings(
n_physical_qubits=7,
n_logical_qubits=1,
distance=3,
generators=["XXXXIII", "IXXIXXI", "IIXXIXX",
"ZZZZIII", "IZZIZZI", "IIZZIZZ"],
x_logicals=["XXXXXXX"],
z_logicals=["ZZZZZZZ"],
)
@guppy
def steane_specify_h(qs: array[qubit, 1]) -> None:
h(qs[0])
@guppy
def steane_impl_h(block: array[qubit, 7]) -> None:
for i in range(len(block)):
h(block[i])
# True => implementation is valid
assert valid_clifford_implementation(steane_specify_h, steane_impl_h, STEANE_DEF)
"""
sem_stabilizers, impl_stabilizers = _compute_clifford_tableaux(
semantic_function,
impl_function,
code_definition,
n_impl_ancillas,
)
# Canonicalize both Clifford Tableaux so that we can test for equality.
sem_stabilizers.canonicalize_all()
impl_stabilizers.canonicalize_all()
return sem_stabilizers == impl_stabilizers