def surface_code_circuit(
    distance: int, num_rounds: int, moment_by_moment: bool = True
) -> cirq.Circuit:
    """Constructs a rotated memory Z surface code circuit with `distance` and `num_rounds`.

    The circuit has `dxd` data qubits and `d ** 2 - 1` measure qubits, where `d` is the distance
    of surface code. For more details on rotated surface codes and qubit indexing, see figure 13
    https://arxiv.org/abs/1111.4022.

    Args:
        distance: Distance of the surface code.
        num_rounds: Number of error correction rounds for memory Z experiment.
        moment_by_moment: If True, the circuit is constructed moment-by-moment instead of
            operation-by-operation. This is useful to benchmark different circuit construction
            patterns for the same circuit.

    Returns:
        A `cirq.Circuit` for surface code memory Z experiment for `distance` and `num_rounds`.
    """

    def ndrange(*ranges: tuple[int, ...]):
        return itertools.product(*[range(*r) for r in ranges])

    data_qubits = {cirq.q(2 * x + 1, 2 * y + 1) for x, y in ndrange((distance,), (distance,))}
    z_measure_qubits = {
        cirq.q(2 * x, 2 * y) for x, y in ndrange((1, distance), (distance + 1,)) if x % 2 != y % 2
    }
    x_measure_qubits = {
        cirq.q(2 * x, 2 * y) for x, y in ndrange((distance + 1,), (1, distance)) if x % 2 == y % 2
    }
    x_order = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
    z_order = [(1, 1), (-1, 1), (1, -1), (-1, -1)]
    surface_code_cycle = rotated_surface_code_memory_z_cycle(
        data_qubits, x_measure_qubits, z_measure_qubits, x_order, z_order
    )
    if moment_by_moment:
        return cirq.Circuit(
            surface_code_cycle * num_rounds, cirq.Moment(cirq.measure_each(*data_qubits))
        )
    else:
        return cirq.Circuit(
            [*surface_code_cycle.all_operations()] * num_rounds, cirq.measure_each(*data_qubits)
        )
Constructs a rotated memory Z surface code circuit with `distance` and `num_rounds`.

    The circuit has `dxd` data qubits and `d ** 2 - 1` measure qubits, where `d` is the distance
    of surface code. For more details on rotated surface codes and qubit indexing, see figure 13
    https://arxiv.org/abs/1111.4022.

    Args:
        distance: Distance of the surface code.
        num_rounds: Number of error correction rounds for memory Z experiment.
        moment_by_moment: If True, the circuit is constructed moment-by-moment instead of
            operation-by-operation. This is useful to benchmark different circuit construction
            patterns for the same circuit.

    Returns:
        A `cirq.Circuit` for surface code memory Z experiment for `distance` and `num_rounds`.
    
benchmarks/circuit_construction.py