def canonicalize_gates(gates: LogicalGates
        ) -> Dict[frozenset, LogicalGates]:
        """Canonicalizes a set of gates by the qubits they act on.

        Takes a set of gates specified by ordered sequences of logical
        indices, and groups those that act on the same qubits regardless of
        order."""
        canonicalized_gates = defaultdict(dict
            ) # type: DefaultDict[frozenset, LogicalGates]
        for indices, gate in gates.items():
            indices = tuple(indices)
            canonicalized_gates[frozenset(indices)][indices] = gate
        return {canonical_indices: dict(list(gates.items()))
                for canonical_indices, gates in canonicalized_gates.items()}