If I have a cirq.Circuit as follows:

a, b, c = cirq.LineQubit.range(3)
circuit = cirq.Circuit(

I use stimcirq to convert it to a stim circuit and get circuit as

    X 0
    Y 1
    X 2

The cirq.X operation within the same moment cannot be formatted in a compact format like "X 0, 2".

Is there a way to automatically format the converted stim circuit in a compact style?


1 Answer 1


There isn't an option to request that the operations be re-ordered so that they group better. (Cirq moments do keep track of operation order, so it makes sense for the conversion to by default attempt to preserve this order, so that round trip conversions preserve more details.)

You can write code to modify the cirq circuit yourself, so that identical operations end up together:

from typing import Callable, Any, List, Dict

import cirq

def group_by(items, *, key: Callable[[Any], Any]) -> Dict[Any, List[Any]]:
    result: Dict[Any, List[Any]] = {}
    for item in items:
        item_key = key(item)
        result.setdefault(item_key, []).append(item)
    return result

def moment_with_grouped_operations(moment: cirq.Moment) -> cirq.Moment:
    gate_groups = group_by(moment.operations, key=lambda e: e.gate)
    return cirq.Moment(gate_groups.values())

def circuit_with_grouped_operations(circuit: cirq.AbstractCircuit) -> cirq.FrozenCircuit:
    return cirq.FrozenCircuit(moment_with_grouped_operations(m) for m in circuit)

Testing it:

import stimcirq
a, b, c = cirq.LineQubit.range(3)
circuit = cirq.Circuit(
# prints:
# X 0 2
# Y 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.