Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add stimcirq tags #862

Closed
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 94 additions & 63 deletions glue/cirq/stimcirq/_cirq_to_stim.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@


def cirq_circuit_to_stim_circuit(
circuit: cirq.AbstractCircuit, *, qubit_to_index_dict: Optional[Dict[cirq.Qid, int]] = None
circuit: cirq.AbstractCircuit,
*,
qubit_to_index_dict: Optional[Dict[cirq.Qid, int]] = None,
custom_op_conversion_func: Callable | None = None
emma-louise-rosenfeld marked this conversation as resolved.
Show resolved Hide resolved
) -> stim.Circuit:
"""Converts a cirq circuit into an equivalent stim circuit.

Expand Down Expand Up @@ -90,11 +93,15 @@ def _stim_conversion_(

edit_circuit.append_operation("H", targets)
"""
return cirq_circuit_to_stim_data(circuit, q2i=qubit_to_index_dict, flatten=False)[0]
return cirq_circuit_to_stim_data(circuit, q2i=qubit_to_index_dict, flatten=False, custom_op_conversion_func=custom_op_conversion_func)[0]


def cirq_circuit_to_stim_data(
circuit: cirq.AbstractCircuit, *, q2i: Optional[Dict[cirq.Qid, int]] = None, flatten: bool = False,
circuit: cirq.AbstractCircuit,
*,
q2i: Optional[Dict[cirq.Qid, int]] = None,
flatten: bool = False,
custom_op_conversion_func: Callable | None = None,
) -> Tuple[stim.Circuit, List[Tuple[str, int]]]:
"""Converts a Cirq circuit into a Stim circuit and also metadata about where measurements go."""
if q2i is None:
Expand All @@ -111,15 +118,17 @@ def cirq_circuit_to_stim_data(
elif isinstance(q, cirq.GridQubit):
helper.out.append_operation("QUBIT_COORDS", [q2i[q]], [q.row, q.col])

helper.process_moments(circuit)
helper.process_moments(circuit, custom_op_conversion_func=custom_op_conversion_func)
return helper.out, helper.key_out


StimTypeHandler = Callable[[stim.Circuit, cirq.Gate, List[int]], None]


@functools.lru_cache(maxsize=1)
def gate_to_stim_append_func() -> Dict[cirq.Gate, Callable[[stim.Circuit, List[int]], None]]:
def gate_to_stim_append_func() -> (
Dict[cirq.Gate, Callable[[stim.Circuit, List[int]], None]]
):
"""A dictionary mapping specific gate instances to stim circuit appending functions."""
x = (cirq.X, False)
y = (cirq.Y, False)
Expand Down Expand Up @@ -161,38 +170,38 @@ def do(c, t):
cirq.ResetChannel(): use("R"),
# Identities.
cirq.I: use("I"),
cirq.H ** 0: do_nothing,
cirq.X ** 0: do_nothing,
cirq.Y ** 0: do_nothing,
cirq.Z ** 0: do_nothing,
cirq.ISWAP ** 0: do_nothing,
cirq.SWAP ** 0: do_nothing,
cirq.H**0: do_nothing,
cirq.X**0: do_nothing,
cirq.Y**0: do_nothing,
cirq.Z**0: do_nothing,
cirq.ISWAP**0: do_nothing,
cirq.SWAP**0: do_nothing,
# Common named gates.
cirq.H: use("H"),
cirq.X: use("X"),
cirq.Y: use("Y"),
cirq.Z: use("Z"),
cirq.X ** 0.5: use("SQRT_X"),
cirq.X ** -0.5: use("SQRT_X_DAG"),
cirq.Y ** 0.5: use("SQRT_Y"),
cirq.Y ** -0.5: use("SQRT_Y_DAG"),
cirq.Z ** 0.5: use("SQRT_Z"),
cirq.Z ** -0.5: use("SQRT_Z_DAG"),
cirq.X**0.5: use("SQRT_X"),
cirq.X**-0.5: use("SQRT_X_DAG"),
cirq.Y**0.5: use("SQRT_Y"),
cirq.Y**-0.5: use("SQRT_Y_DAG"),
cirq.Z**0.5: use("SQRT_Z"),
cirq.Z**-0.5: use("SQRT_Z_DAG"),
cirq.CNOT: use("CNOT"),
cirq.CZ: use("CZ"),
cirq.ISWAP: use("ISWAP"),
cirq.ISWAP ** -1: use("ISWAP_DAG"),
cirq.ISWAP ** 2: use("Z"),
cirq.ISWAP**-1: use("ISWAP_DAG"),
cirq.ISWAP**2: use("Z"),
cirq.SWAP: use("SWAP"),
cirq.X.controlled(1): use("CX"),
cirq.Y.controlled(1): use("CY"),
cirq.Z.controlled(1): use("CZ"),
cirq.XX ** 0.5: use("SQRT_XX"),
cirq.YY ** 0.5: use("SQRT_YY"),
cirq.ZZ ** 0.5: use("SQRT_ZZ"),
cirq.XX ** -0.5: use("SQRT_XX_DAG"),
cirq.YY ** -0.5: use("SQRT_YY_DAG"),
cirq.ZZ ** -0.5: use("SQRT_ZZ_DAG"),
cirq.XX**0.5: use("SQRT_XX"),
cirq.YY**0.5: use("SQRT_YY"),
cirq.ZZ**0.5: use("SQRT_ZZ"),
cirq.XX**-0.5: use("SQRT_XX_DAG"),
cirq.YY**-0.5: use("SQRT_YY_DAG"),
cirq.ZZ**-0.5: use("SQRT_ZZ_DAG"),
# All 24 cirq.SingleQubitCliffordGate instances.
sqcg(x, y): use("SQRT_X_DAG"),
sqcg(x, ny): use("SQRT_X"),
Expand Down Expand Up @@ -233,8 +242,12 @@ def gate_type_to_stim_append_func() -> Dict[Type[cirq.Gate], StimTypeHandler]:
"""A dictionary mapping specific gate types to stim circuit appending functions."""
return {
cirq.ControlledGate: cast(StimTypeHandler, _stim_append_controlled_gate),
cirq.DensePauliString: cast(StimTypeHandler, _stim_append_dense_pauli_string_gate),
cirq.MutableDensePauliString: cast(StimTypeHandler, _stim_append_dense_pauli_string_gate),
cirq.DensePauliString: cast(
StimTypeHandler, _stim_append_dense_pauli_string_gate
),
cirq.MutableDensePauliString: cast(
StimTypeHandler, _stim_append_dense_pauli_string_gate
),
cirq.AsymmetricDepolarizingChannel: cast(
StimTypeHandler, _stim_append_asymmetric_depolarizing_channel
),
Expand All @@ -245,10 +258,14 @@ def gate_type_to_stim_append_func() -> Dict[Type[cirq.Gate], StimTypeHandler]:
"Z_ERROR", t, cast(cirq.PhaseFlipChannel, g).p
),
cirq.PhaseDampingChannel: lambda c, g, t: c.append_operation(
"Z_ERROR", t, 0.5 - math.sqrt(1 - cast(cirq.PhaseDampingChannel, g).gamma) / 2
"Z_ERROR",
t,
0.5 - math.sqrt(1 - cast(cirq.PhaseDampingChannel, g).gamma) / 2,
),
cirq.RandomGateChannel: cast(StimTypeHandler, _stim_append_random_gate_channel),
cirq.DepolarizingChannel: cast(StimTypeHandler, _stim_append_depolarizing_channel),
cirq.DepolarizingChannel: cast(
StimTypeHandler, _stim_append_depolarizing_channel
),
}


Expand Down Expand Up @@ -335,28 +352,30 @@ def _stim_append_asymmetric_depolarizing_channel(
"PAULI_CHANNEL_2",
t,
[
g.error_probabilities.get('IX', 0),
g.error_probabilities.get('IY', 0),
g.error_probabilities.get('IZ', 0),
g.error_probabilities.get('XI', 0),
g.error_probabilities.get('XX', 0),
g.error_probabilities.get('XY', 0),
g.error_probabilities.get('XZ', 0),
g.error_probabilities.get('YI', 0),
g.error_probabilities.get('YX', 0),
g.error_probabilities.get('YY', 0),
g.error_probabilities.get('YZ', 0),
g.error_probabilities.get('ZI', 0),
g.error_probabilities.get('ZX', 0),
g.error_probabilities.get('ZY', 0),
g.error_probabilities.get('ZZ', 0),
]
g.error_probabilities.get("IX", 0),
g.error_probabilities.get("IY", 0),
g.error_probabilities.get("IZ", 0),
g.error_probabilities.get("XI", 0),
g.error_probabilities.get("XX", 0),
g.error_probabilities.get("XY", 0),
g.error_probabilities.get("XZ", 0),
g.error_probabilities.get("YI", 0),
g.error_probabilities.get("YX", 0),
g.error_probabilities.get("YY", 0),
g.error_probabilities.get("YZ", 0),
g.error_probabilities.get("ZI", 0),
g.error_probabilities.get("ZX", 0),
g.error_probabilities.get("ZY", 0),
g.error_probabilities.get("ZZ", 0),
],
)
else:
raise NotImplementedError(f'cirq-to-stim gate {g!r}')
raise NotImplementedError(f"cirq-to-stim gate {g!r}")


def _stim_append_depolarizing_channel(c: stim.Circuit, g: cirq.DepolarizingChannel, t: List[int]):
def _stim_append_depolarizing_channel(
c: stim.Circuit, g: cirq.DepolarizingChannel, t: List[int]
):
if g.num_qubits() == 1:
c.append_operation("DEPOLARIZE1", t, g.p)
elif g.num_qubits() == 2:
Expand All @@ -383,10 +402,14 @@ def _stim_append_controlled_gate(c: stim.Circuit, g: cirq.ControlledGate, t: Lis
raise TypeError(f"Phase kickback from {g!r} isn't a stabilizer operation.")
return

raise TypeError(f"Don't know how to turn controlled gate {g!r} into Stim operations.")
raise TypeError(
f"Don't know how to turn controlled gate {g!r} into Stim operations."
)


def _stim_append_random_gate_channel(c: stim.Circuit, g: cirq.RandomGateChannel, t: List[int]):
def _stim_append_random_gate_channel(
c: stim.Circuit, g: cirq.RandomGateChannel, t: List[int]
):
if g.sub_gate in [cirq.X, cirq.Y, cirq.Z]:
c.append_operation(f"{g.sub_gate}_ERROR", t, g.probability)
elif isinstance(g.sub_gate, cirq.DensePauliString):
Expand All @@ -407,32 +430,38 @@ def __init__(self):
self.have_seen_loop = False
self.flatten = False

def process_circuit_operation_into_repeat_block(self, op: cirq.CircuitOperation) -> None:
def process_circuit_operation_into_repeat_block(
self, op: cirq.CircuitOperation, custom_op_conversion_func: Callable | None
) -> None:
if self.flatten or op.repetitions == 1:
moments = cirq.unroll_circuit_op(cirq.Circuit(op), deep=False, tags_to_check=None).moments
self.process_moments(moments)
self.out = self.out[:-1] # Remove a trailing TICK (to avoid double TICK)
moments = cirq.unroll_circuit_op(
cirq.Circuit(op), deep=False, tags_to_check=None
).moments
self.process_moments(moments, custom_op_conversion_func=custom_op_conversion_func)
self.out = self.out[:-1] # Remove a trailing TICK (to avoid double TICK)
return

child = CirqToStimHelper()
child.key_out = self.key_out
child.q2i = self.q2i
child.have_seen_loop = True
self.have_seen_loop = True
child.process_moments(op.transform_qubits(lambda q: op.qubit_map.get(q, q)).circuit)
child.process_moments(
op.transform_qubits(lambda q: op.qubit_map.get(q, q)).circuit, custom_op_conversion_func=custom_op_conversion_func
)
self.out += child.out * op.repetitions

def process_operations(self, operations: Iterable[cirq.Operation]) -> None:
def process_operations(self, operations: Iterable[cirq.Operation], custom_op_conversion_func: Callable | None) -> None:
g2f = gate_to_stim_append_func()
t2f = gate_type_to_stim_append_func()
for op in operations:
assert isinstance(op, cirq.Operation)
op = op.untagged
op = op.untagged if custom_op_conversion_func is None else custom_op_conversion_func(op)
gate = op.gate
targets = [self.q2i[q] for q in op.qubits]

custom_method = getattr(
op, '_stim_conversion_', getattr(gate, '_stim_conversion_', None)
op, "_stim_conversion_", getattr(gate, "_stim_conversion_", None)
)
if custom_method is not None:
custom_method(
Expand All @@ -445,7 +474,7 @@ def process_operations(self, operations: Iterable[cirq.Operation]) -> None:
continue

if isinstance(op, cirq.CircuitOperation):
self.process_circuit_operation_into_repeat_block(op)
self.process_circuit_operation_into_repeat_block(op, custom_op_conversion_func=custom_op_conversion_func)
continue

# Special case measurement, because of its metadata.
Expand Down Expand Up @@ -483,14 +512,16 @@ def process_operations(self, operations: Iterable[cirq.Operation]) -> None:
f"- It doesn't have a _stim_conversion_ method.\n"
) from ex

def process_moment(self, moment: cirq.Moment):
def process_moment(self, moment: cirq.Moment, custom_op_conversion_func: Callable | None):
length_before = len(self.out)
self.process_operations(moment)
self.process_operations(moment, custom_op_conversion_func=custom_op_conversion_func)

# Append a TICK, unless it was already handled by an internal REPEAT block.
if length_before == len(self.out) or not isinstance(self.out[-1], stim.CircuitRepeatBlock):
if length_before == len(self.out) or not isinstance(
self.out[-1], stim.CircuitRepeatBlock
):
self.out.append_operation("TICK", [])

def process_moments(self, moments: Iterable[cirq.Moment]):
def process_moments(self, moments: Iterable[cirq.Moment], custom_op_conversion_func: Callable | None):
for moment in moments:
self.process_moment(moment)
self.process_moment(moment, custom_op_conversion_func=custom_op_conversion_func)
Loading