Convert cirq circuit to stim cirq in a compact style

If I have a cirq.Circuit as follows:

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


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

stim.Circuit('''
X 0
Y 1
X 2
TICK
''')


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?

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(
cirq.X(a),
cirq.Y(b),
cirq.X(c),
)
print(stimcirq.cirq_circuit_to_stim_circuit(circuit_with_grouped_operations(circuit)))
# prints:
# X 0 2
# Y 1
# TICK