INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Raise an element of the Pauli algebra to a non-negative integer power.
def pauli_pow(pauli: Pauli, exponent: int) -> Pauli: """ Raise an element of the Pauli algebra to a non-negative integer power. """ if not isinstance(exponent, int) or exponent < 0: raise ValueError("The exponent must be a non-negative integer.") if exponent == 0: return Pauli.identity() if exponent == 1: return pauli # https://en.wikipedia.org/wiki/Exponentiation_by_squaring y = Pauli.identity() x = pauli n = exponent while n > 1: if n % 2 == 0: # Even x = x * x n = n // 2 else: # Odd y = x * y x = x * x n = (n - 1) // 2 return x * y
Returns: True if Pauli elements are almost identical.
def paulis_close(pauli0: Pauli, pauli1: Pauli, tolerance: float = TOLERANCE) \ -> bool: """Returns: True if Pauli elements are almost identical.""" pauli = pauli0 - pauli1 d = sum(abs(coeff)**2 for _, coeff in pauli.terms) return d <= tolerance
Return true if the two elements of the Pauli algebra commute. i.e. if element0 * element1 == element1 * element0 Derivation similar to arXiv:1405.5749v2 for the check_commutation step in the Raesi, Wiebe, Sanders algorithm (arXiv:1108.4318, 2011).
def paulis_commute(element0: Pauli, element1: Pauli) -> bool: """ Return true if the two elements of the Pauli algebra commute. i.e. if element0 * element1 == element1 * element0 Derivation similar to arXiv:1405.5749v2 for the check_commutation step in the Raesi, Wiebe, Sanders algorithm (arXiv:1108.4318, 2011). """ def _coincident_parity(term0: PauliTerm, term1: PauliTerm) -> bool: non_similar = 0 key = itemgetter(0) op0 = term0[0] op1 = term1[0] for _, qops in groupby(heapq.merge(op0, op1, key=key), key=key): listqops = list(qops) if len(listqops) == 2 and listqops[0][1] != listqops[1][1]: non_similar += 1 return non_similar % 2 == 0 for term0, term1 in product(element0, element1): if not _coincident_parity(term0, term1): return False return True
Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2
def pauli_commuting_sets(element: Pauli) -> Tuple[Pauli, ...]: """Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2 """ if len(element) < 2: return (element,) groups: List[Pauli] = [] # typing: List[Pauli] for term in element: pterm = Pauli((term,)) assigned = False for i, grp in enumerate(groups): if paulis_commute(grp, pterm): groups[i] = grp + pterm assigned = True break if not assigned: groups.append(pterm) return tuple(groups)
Converts a numpy array to the backend's tensor object
def astensor(array: TensorLike) -> BKTensor: """Converts a numpy array to the backend's tensor object """ array = np.asarray(array, dtype=CTYPE) return array
Converts a numpy array to the backend's tensor object, and reshapes to [2]*N (So the number of elements must be a power of 2)
def astensorproduct(array: TensorLike) -> BKTensor: """Converts a numpy array to the backend's tensor object, and reshapes to [2]*N (So the number of elements must be a power of 2) """ tensor = astensor(array) N = int(math.log2(size(tensor))) array = tensor.reshape([2]*N) return array
Return the inner product between two tensors
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two tensors""" # Note: Relying on fact that vdot flattens arrays return np.vdot(tensor0, tensor1)
Returns the matrix diagonal of the product tensor
def productdiag(tensor: BKTensor) -> BKTensor: """Returns the matrix diagonal of the product tensor""" # DOCME: Explain N = rank(tensor) tensor = reshape(tensor, [2**(N//2), 2**(N//2)]) tensor = np.diag(tensor) tensor = reshape(tensor, [2]*(N//2)) return tensor
r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor
def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor: r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and K/2 for covariant (bra) indices, e.g. :math:`A^{a_0,a_1}_{a_2,a_3}` for a 2-qubit gate. The given indices of A are contracted against B, replacing the given positions. E.g. ``tensormul(A, B, [0,2])`` is equivalent to .. math:: C^{a_0,b_1,a_1} =\sum_{i_0,i_1} A^{a_0,a_1}_{i_0,i_1} B^{i_0,b_1,i_1} Args: tensor0: A tensor product representation of a gate tensor1: A tensor product representation of a gate or state indices: List of indices of tensor1 on which to act. Returns: Resultant state or gate tensor """ # Note: This method is the critical computational core of QuantumFlow # We currently have two implementations, one that uses einsum, the other # using matrix multiplication # # numpy: # einsum is much faster particularly for small numbers of qubits # tensorflow: # Little different is performance, but einsum would restrict the # maximum number of qubits to 26 (Because tensorflow only allows 26 # einsum subscripts at present] # torch: # einsum is slower than matmul N = rank(tensor1) K = rank(tensor0) // 2 assert K == len(indices) out = list(EINSUM_SUBSCRIPTS[0:N]) left_in = list(EINSUM_SUBSCRIPTS[N:N+K]) left_out = [out[idx] for idx in indices] right = list(EINSUM_SUBSCRIPTS[0:N]) for idx, s in zip(indices, left_in): right[idx] = s subscripts = ''.join(left_out + left_in + [','] + right + ['->'] + out) # print('>>>', K, N, subscripts) tensor = einsum(subscripts, tensor0, tensor1) return tensor
Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values.
def invert_map(mapping: dict, one_to_one: bool = True) -> dict: """Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values. """ if one_to_one: inv_map = {value: key for key, value in mapping.items()} else: inv_map = {} for key, value in mapping.items(): inv_map.setdefault(value, set()).add(key) return inv_map
Converts a sequence of bits to an integer. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4
def bitlist_to_int(bitlist: Sequence[int]) -> int: """Converts a sequence of bits to an integer. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4 """ return int(''.join([str(d) for d in bitlist]), 2)
Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0]
def int_to_bitlist(x: int, pad: int = None) -> Sequence[int]: """Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0] """ if pad is None: form = '{:0b}' else: form = '{:0' + str(pad) + 'b}' return [int(b) for b in form.format(x)]
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
def deprecated(func: Callable) -> Callable: """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" @functools.wraps(func) def _new_func(*args: Any, **kwargs: Any) -> Any: warnings.simplefilter('always', DeprecationWarning) # turn off filter warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=2) warnings.simplefilter('default', DeprecationWarning) # reset filter return func(*args, **kwargs) return _new_func
Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem.
def spanning_tree_count(graph: nx.Graph) -> int: """Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem. """ laplacian = nx.laplacian_matrix(graph).toarray() comatrix = laplacian[:-1, :-1] det = np.linalg.det(comatrix) count = int(round(det)) return count
Return the octagonal tiling graph (4.8.8, truncated square tiling, truncated quadrille) of MxNx8 nodes The 'positions' node attribute gives node coordinates for the octagonal tiling. (Nodes are located on a square lattice, and edge lengths are uneven)
def octagonal_tiling_graph(M: int, N: int) -> nx.Graph: """Return the octagonal tiling graph (4.8.8, truncated square tiling, truncated quadrille) of MxNx8 nodes The 'positions' node attribute gives node coordinates for the octagonal tiling. (Nodes are located on a square lattice, and edge lengths are uneven) """ grp = nx.Graph() octogon = [[(1, 0), (0, 1)], [(0, 1), (0, 2)], [(0, 2), (1, 3)], [(1, 3), (2, 3)], [(2, 3), (3, 2)], [(3, 2), (3, 1)], [(3, 1), (2, 0)], [(2, 0), (1, 0)]] left = [[(1, 0), (1, -1)], [(2, 0), (2, -1)]] up = [[(0, 1), (-1, 1)], [(0, 2), (-1, 2)]] for m in range(M): for n in range(N): edges = octogon if n != 0: edges = edges + left if m != 0: edges = edges + up for (x0, y0), (x1, y1) in edges: grp.add_edge((m*4+x0, n*4+y0), (m*4+x1, n*4+y1)) positions = {node: node for node in grp} nx.set_node_attributes(grp, positions, 'positions') return grp
r""" Implements Euler's formula :math:`\text{cis}(x) = e^{i \pi x} = \cos(x) + i \sin(x)`
def cis(x: float) -> complex: r""" Implements Euler's formula :math:`\text{cis}(x) = e^{i \pi x} = \cos(x) + i \sin(x)` """ return np.cos(x) + 1.0j * np.sin(x)
Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: """Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 Raises: ValueError: If cannot rationalize float """ if denominators is None: denominators = _DENOMINATORS frac = Fraction.from_float(flt).limit_denominator() if frac.denominator not in denominators: raise ValueError('Cannot rationalize') return frac
Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float
def symbolize(flt: float) -> sympy.Symbol: """Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float """ try: ratio = rationalize(flt) res = sympy.simplify(ratio) except ValueError: ratio = rationalize(flt/np.pi) res = sympy.simplify(ratio) * sympy.pi return res
Returns an image of a pyquil circuit. See circuit_to_latex() for more details.
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover """Returns an image of a pyquil circuit. See circuit_to_latex() for more details. """ circ = pyquil_to_circuit(program) latex = circuit_to_latex(circ) img = render_latex(latex) return img
Convert a QuantumFlow circuit to a pyQuil program
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: """Convert a QuantumFlow circuit to a pyQuil program""" prog = pyquil.Program() for elem in circuit.elements: if isinstance(elem, Gate) and elem.name in QUIL_GATES: params = list(elem.params.values()) if elem.params else [] prog.gate(elem.name, params, elem.qubits) elif isinstance(elem, Measure): prog.measure(elem.qubit, elem.cbit) else: # FIXME: more informative error message raise ValueError('Cannot convert operation to pyquil') return prog
Convert a protoquil pyQuil program to a QuantumFlow Circuit
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinstance(inst, pyquil.Halt): # Ignore continue if isinstance(inst, pyquil.Pragma): # TODO Barrier? continue elif isinstance(inst, pyquil.Measurement): circ += Measure(inst.qubit.index) # elif isinstance(inst, pyquil.ResetQubit): # TODO # continue elif isinstance(inst, pyquil.Gate): defgate = STDGATES[inst.name] gate = defgate(*inst.params) qubits = [q.index for q in inst.qubits] gate = gate.relabel(qubits) circ += gate else: raise ValueError('PyQuil program is not protoquil') return circ
Parse a quil program and return a Program object
def quil_to_program(quil: str) -> Program: """Parse a quil program and return a Program object""" pyquil_instructions = pyquil.parser.parse(quil) return pyquil_to_program(pyquil_instructions)
Convert a pyQuil program to a QuantumFlow Program
def pyquil_to_program(program: pyquil.Program) -> Program: """Convert a pyQuil program to a QuantumFlow Program""" def _reg(mem: Any) -> Any: if isinstance(mem, pyquil.MemoryReference): return Register(mem.name)[mem.offset] return mem prog = Program() for inst in program: if isinstance(inst, pyquil.Gate): qubits = [q.index for q in inst.qubits] if inst.name in STDGATES: defgate = STDGATES[inst.name] gate = defgate(*inst.params) gate = gate.relabel(qubits) prog += gate else: prog += Call(inst.name, inst.params, qubits) elif isinstance(inst, pyquil.ClassicalEqual): prog += EQ(_reg(inst.target), _reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalLessThan): prog += LT(_reg(inst.target), _reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalLessEqual): prog += LE(_reg(inst.target), _reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalGreaterThan): prog += GT(_reg(inst.target), _reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalGreaterEqual): prog += GE(_reg(inst.target), _reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalAdd): prog += Add(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalMul): prog += Mul(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalDiv): prog += Div(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalSub): prog += Sub(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalAnd): prog += And(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalExchange): prog += Exchange(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalInclusiveOr): prog += Ior(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalMove): # Also handles deprecated ClassicalTrue and ClassicalFalse prog += Move(_reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalNeg): prog += Neg(_reg(inst.target)) elif isinstance(inst, pyquil.ClassicalNot): prog += Not(_reg(inst.target)) elif isinstance(inst, pyquil.ClassicalExclusiveOr): target = _reg(inst.left) source = _reg(inst.right) prog += Xor(target, source) elif isinstance(inst, pyquil.Declare): prog += Declare(inst.name, inst.memory_type, inst.memory_size, inst.shared_region) elif isinstance(inst, pyquil.Halt): prog += Halt() elif isinstance(inst, pyquil.Jump): prog += Jump(inst.target.name) elif isinstance(inst, pyquil.JumpTarget): prog += Label(inst.label.name) elif isinstance(inst, pyquil.JumpWhen): prog += JumpWhen(inst.target.name, _reg(inst.condition)) elif isinstance(inst, pyquil.JumpUnless): prog += JumpUnless(inst.target.name, _reg(inst.condition)) elif isinstance(inst, pyquil.Pragma): prog += Pragma(inst.command, inst.args, inst.freeform_string) elif isinstance(inst, pyquil.Measurement): if inst.classical_reg is None: prog += Measure(inst.qubit.index) else: prog += Measure(inst.qubit.index, _reg(inst.classical_reg)) elif isinstance(inst, pyquil.Nop): prog += Nop() elif isinstance(inst, pyquil.Wait): prog += Wait() elif isinstance(inst, pyquil.Reset): prog += Reset() elif isinstance(inst, pyquil.ResetQubit): prog += Reset(inst.qubit) elif isinstance(inst, pyquil.ClassicalStore): prog += Store(inst.target, _reg(inst.left), _reg(inst.right)) elif isinstance(inst, pyquil.ClassicalLoad): prog += Load(_reg(inst.target), inst.left, _reg(inst.right)) # elif isinstance(inst, pyquil.ClassicalConvert): # prog += Convert(inst.target, _reg(inst.left), _reg(inst.right)) else: raise ValueError('Unknown pyQuil instruction: {}' .format(str(inst))) # pragma: no cover return prog
Convert a QuantumFlow state to a pyQuil Wavefunction
def state_to_wavefunction(state: State) -> pyquil.Wavefunction: """Convert a QuantumFlow state to a pyQuil Wavefunction""" # TODO: qubits? amplitudes = state.vec.asarray() # pyQuil labels states backwards. amplitudes = amplitudes.transpose() amplitudes = amplitudes.reshape([amplitudes.size]) return pyquil.Wavefunction(amplitudes)
Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM': """ Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program """ assert self.status in ['connected', 'done'] prog = quil_to_program(str(binary)) self._prog = prog self.program = binary self.status = 'loaded' return self
Run a previously loaded program
def run(self) -> 'QuantumFlowQVM': """Run a previously loaded program""" assert self.status in ['loaded'] self.status = 'running' self._ket = self._prog.run() # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's # QuantumComputer calls wait() after run, which expects state to be # 'running', and whose only effect to is to set state to 'done' return self
Return the wavefunction of a completed program.
def wavefunction(self) -> pyquil.Wavefunction: """ Return the wavefunction of a completed program. """ assert self.status == 'done' assert self._ket is not None wavefn = state_to_wavefunction(self._ket) return wavefn
Return a list of circuit identities, each consisting of a name, and two equivalent Circuits.
def identities(): """ Return a list of circuit identities, each consisting of a name, and two equivalent Circuits.""" circuit_identities = [] # Pick random parameter theta = np.pi * np.random.uniform() # Single qubit gate identities name = "Hadamard is own inverse" circ0 = Circuit([H(0), H(0)]) circ1 = Circuit([I(0)]) circuit_identities.append([name, circ0, circ1]) name = "Hadamards convert X to Z" circ0 = Circuit([H(0), X(0), H(0)]) circ1 = Circuit([Z(0)]) circuit_identities.append([name, circ0, circ1]) name = "Hadamards convert Z to X" circ0 = Circuit([H(0), Z(0), H(0)]) circ1 = Circuit([X(0)]) circuit_identities.append([name, circ0, circ1]) name = "S sandwich converts X to Y" circ0 = Circuit([S(0).H, X(0), S(0)]) circ1 = Circuit([Y(0)]) circuit_identities.append([name, circ0, circ1]) name = "S sandwich converts Y to X" circ0 = Circuit([S(0), Y(0), S(0).H]) circ1 = Circuit([X(0)]) circuit_identities.append([name, circ0, circ1]) name = "Hadamards convert RZ to RX" circ0 = Circuit([H(0), RZ(theta, 0), H(0)]) circ1 = Circuit([RX(theta, 0)]) circuit_identities.append([name, circ0, circ1]) # ZYZ Decompositions name = "Hadamard ZYZ decomposition" circ0 = Circuit([H(0)]) circ1 = Circuit([Z(0), Y(0)**0.5]) circuit_identities.append([name, circ0, circ1]) # CNOT identities name = "CZ to CNOT" circ0 = Circuit([CZ(0, 1)]) circ1 = Circuit([H(1), CNOT(0, 1), H(1)]) circuit_identities.append([name, circ0, circ1]) name = "SWAP to 3 CNOTs" circ0 = Circuit([SWAP(0, 1)]) circ1 = Circuit([CNOT(0, 1), CNOT(1, 0), CNOT(0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "SWAP to 3 CZs" circ0 = Circuit([SWAP(0, 1)]) circ1 = Circuit([H(1), CZ(0, 1), H(0), H(1), CZ(1, 0), H(0), H(1), CZ(0, 1), H(1)]) circuit_identities.append([name, circ0, circ1]) name = "ISWAP decomposition to SWAP and CNOT" circ0 = Circuit([ISWAP(0, 1)]) circ1 = Circuit([SWAP(0, 1), H(1), CNOT(0, 1), H(1), S(0), S(1)]) circuit_identities.append([name, circ0, circ1]) name = "ISWAP decomposition to SWAP and CZ" # This makes it clear why you can commute RZ's across ISWAP circ0 = Circuit([ISWAP(0, 1)]) circ1 = Circuit([SWAP(0, 1), CZ(0, 1), S(0), S(1)]) circuit_identities.append([name, circ0, circ1]) # http://info.phys.unm.edu/~caves/courses/qinfo-f14/lectures/lectures21-23.pdf name = "CNOT sandwich with X on control" circ0 = Circuit([CNOT(0, 1), X(0), CNOT(0, 1)]) circ1 = Circuit([X(0), X(1)]) circuit_identities.append([name, circ0, circ1]) # http://info.phys.unm.edu/~caves/courses/qinfo-f14/lectures/lectures21-23.pdf name = "CNOT sandwich with Z on target" circ0 = Circuit([CNOT(0, 1), Z(1), CNOT(0, 1)]) circ1 = Circuit([Z(0), Z(1)]) circuit_identities.append([name, circ0, circ1]) name = "DCNOT (Double-CNOT) to iSWAP" circ0 = Circuit([CNOT(0, 1), CNOT(1, 0)]) circ1 = Circuit([H(0), S(0).H, S(1).H, ISWAP(0, 1), H(1)]) circuit_identities.append([name, circ0, circ1]) # Commuting single qubit gates across 2 qubit games name = "Commute X on CNOT target" circ0 = Circuit([X(1), CNOT(0, 1)]) circ1 = Circuit([CNOT(0, 1), X(1)]) circuit_identities.append([name, circ0, circ1]) name = "Commute X on CNOT control" circ0 = Circuit([X(0), CNOT(0, 1)]) circ1 = Circuit([CNOT(0, 1), X(0), X(1)]) circuit_identities.append([name, circ0, circ1]) name = "Commute Z on CNOT target" circ0 = Circuit([Z(1), CNOT(0, 1)]) circ1 = Circuit([CNOT(0, 1), Z(0), Z(1)]) circuit_identities.append([name, circ0, circ1]) name = "Commute Z on CNOT control" circ0 = Circuit([Z(0), CNOT(0, 1)]) circ1 = Circuit([CNOT(0, 1), Z(0)]) circuit_identities.append([name, circ0, circ1]) # Canonical gate identities name = "Canonical gates: CZ to ZZ" circ0 = Circuit([CZ(0, 1), S(0), S(1)]) circ1 = Circuit([ZZ(0.5, 0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "Canonical gates: XX to ZZ" circ0 = Circuit([H(0), H(1), XX(0.5, 0, 1), H(0), H(1)]) circ1 = Circuit([ZZ(0.5, 0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "Canonical gates: CNOT to XX" circ0 = Circuit([CNOT(0, 1)]) circ1 = Circuit([H(0), XX(0.5, 0, 1), H(0), H(1), S(0).H, S(1).H, H(1)]) circuit_identities.append([name, circ0, circ1]) name = "Canonical gates: SWAP to Canonical" circ0 = Circuit([SWAP(0, 1)]) circ1 = Circuit([CANONICAL(0.5, 0.5, 0.5, 0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "ISWAP to Canonical" circ0 = Circuit([ISWAP(0, 1)]) circ1 = Circuit([CANONICAL(0.5, 0.5, 1.0, 0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "ISWAP to Canonical in Weyl chamber" circ0 = Circuit([ISWAP(0, 1)]) circ1 = Circuit([X(0), CANONICAL(0.5, 0.5, 0.0, 0, 1), X(1)]) circuit_identities.append([name, circ0, circ1]) name = "DCNOT to Canonical" circ0 = Circuit([CNOT(0, 1), CNOT(1, 0)]) circ1 = Circuit([H(0), S(0).H, S(1).H, X(0), CANONICAL(0.5, 0.5, 0.0, 0, 1), X(1), H(1)]) circuit_identities.append([name, circ0, circ1]) # Multi-qubit circuits name = "CNOT controls commute" circ0 = Circuit([CNOT(1, 0), CNOT(1, 2)]) circ1 = Circuit([CNOT(1, 2), CNOT(1, 0)]) circuit_identities.append([name, circ0, circ1]) name = "CNOT targets commute" circ0 = Circuit([CNOT(0, 1), CNOT(2, 1)]) circ1 = Circuit([CNOT(2, 1), CNOT(0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "Commutation of CNOT target/control" circ0 = Circuit([CNOT(0, 1), CNOT(1, 2)]) circ1 = Circuit([CNOT(1, 2), CNOT(0, 2), CNOT(0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "Indirect CNOT and 4 CNOTS with intermediate qubit" circ0 = Circuit([CNOT(0, 2), I(1)]) circ1 = Circuit([CNOT(0, 1), CNOT(1, 2), CNOT(0, 1), CNOT(1, 2)]) circuit_identities.append([name, circ0, circ1]) name = "CZs with shared shared qubit commute" circ0 = Circuit([CZ(0, 1), CZ(1, 2)]) circ1 = Circuit([CZ(1, 2), CZ(0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "Toffoli gate CNOT decomposition" circ0 = Circuit([CCNOT(0, 1, 2)]) circ1 = ccnot_circuit([0, 1, 2]) circuit_identities.append([name, circ0, circ1]) # Parametric circuits name = "ZZ to CNOTs" # 1108.4318 circ0 = Circuit([ZZ(theta/np.pi, 0, 1)]) circ1 = Circuit([CNOT(0, 1), RZ(theta, 1), CNOT(0, 1)]) circuit_identities.append([name, circ0, circ1]) name = "XX to CNOTs" # 1108.4318 circ0 = Circuit([XX(theta/np.pi, 0, 1)]) circ1 = Circuit([H(0), H(1), CNOT(0, 1), RZ(theta, 1), CNOT(0, 1), H(0), H(1)]) circuit_identities.append([name, circ0, circ1]) name = "XX to CNOTs (2)" circ0 = Circuit([XX(theta/np.pi, 0, 1)]) circ1 = Circuit([Y(0)**0.5, Y(1)**0.5, CNOT(0, 1), RZ(theta, 1), CNOT(0, 1), Y(0)**-0.5, Y(1)**-0.5]) circuit_identities.append([name, circ0, circ1]) name = "YY to CNOTs" circ0 = Circuit([YY(theta/np.pi, 0, 1)]) circ1 = Circuit([X(0)**0.5, X(1)**0.5, CNOT(0, 1), RZ(theta, 1), CNOT(0, 1), X(0)**-0.5, X(1)**-0.5]) circuit_identities.append([name, circ0, circ1]) def cphase_to_zz(gate: CPHASE): t = - gate.params['theta'] / (2 * np.pi) q0, q1 = gate.qubits circ = Circuit([ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1)]) return circ def cphase00_to_zz(gate: CPHASE00): t = - gate.params['theta'] / (2 * np.pi) q0, q1 = gate.qubits circ = Circuit([X(0), X(1), ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1), X(0), X(1)]) return circ def cphase01_to_zz(gate: CPHASE00): t = - gate.params['theta'] / (2 * np.pi) q0, q1 = gate.qubits circ = Circuit([X(0), ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1), X(0)]) return circ def cphase10_to_zz(gate: CPHASE00): t = - gate.params['theta'] / (2 * np.pi) q0, q1 = gate.qubits circ = Circuit([X(1), ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1), X(1)]) return circ name = "CPHASE to ZZ" gate = CPHASE(theta, 0, 1) circ0 = Circuit([gate]) circ1 = cphase_to_zz(gate) circuit_identities.append([name, circ0, circ1]) name = "CPHASE00 to ZZ" gate = CPHASE00(theta, 0, 1) circ0 = Circuit([gate]) circ1 = cphase00_to_zz(gate) circuit_identities.append([name, circ0, circ1]) name = "CPHASE01 to ZZ" gate = CPHASE01(theta, 0, 1) circ0 = Circuit([gate]) circ1 = cphase01_to_zz(gate) circuit_identities.append([name, circ0, circ1]) name = "CPHASE10 to ZZ" gate = CPHASE10(theta, 0, 1) circ0 = Circuit([gate]) circ1 = cphase10_to_zz(gate) circuit_identities.append([name, circ0, circ1]) return circuit_identities
Return the value of a tensor
def evaluate(tensor: BKTensor) -> TensorLike: """Return the value of a tensor""" if isinstance(tensor, _DTYPE): if torch.numel(tensor) == 1: return tensor.item() if tensor.numel() == 2: return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy() return tensor
Return the number of dimensions of a tensor
def rank(tensor: BKTensor) -> int: """Return the number of dimensions of a tensor""" if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
Return the inner product between two tensors
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two tensors""" N = torch.numel(tensor0[0]) tensor0_real = tensor0[0].contiguous().view(N) tensor0_imag = tensor0[1].contiguous().view(N) tensor1_real = tensor1[0].contiguous().view(N) tensor1_imag = tensor1[1].contiguous().view(N) res = (torch.matmul(tensor0_real, tensor1_real) + torch.matmul(tensor0_imag, tensor1_imag), torch.matmul(tensor0_real, tensor1_imag) - torch.matmul(tensor0_imag, tensor1_real)) return _DTYPE(res)
Return the quantum fidelity between pure states.
def state_fidelity(state0: State, state1: State) -> bk.BKTensor: """Return the quantum fidelity between pure states.""" assert state0.qubits == state1.qubits # FIXME tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2) return tensor
The Fubini-Study angle between states. Equal to the Burrs angle for pure states.
def state_angle(ket0: State, ket1: State) -> bk.BKTensor: """The Fubini-Study angle between states. Equal to the Burrs angle for pure states. """ return fubini_study_angle(ket0.vec, ket1.vec)
Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle.
def states_close(state0: State, state1: State, tolerance: float = TOLERANCE) -> bool: """Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(state0.vec, state1.vec, tolerance)
Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participation ratio, 1/purity.
def purity(rho: Density) -> bk.BKTensor: """ Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participation ratio, 1/purity. """ tensor = rho.tensor N = rho.qubit_nb matrix = bk.reshape(tensor, [2**N, 2**N]) return bk.trace(bk.matmul(matrix, matrix))
Return the fidelity F(rho0, rho1) between two mixed quantum states. Note: Fidelity cannot be calculated entirely within the tensor backend.
def fidelity(rho0: Density, rho1: Density) -> float: """Return the fidelity F(rho0, rho1) between two mixed quantum states. Note: Fidelity cannot be calculated entirely within the tensor backend. """ assert rho0.qubit_nb == rho1.qubit_nb # FIXME rho1 = rho1.permute(rho0.qubits) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) fid = np.real((np.trace(sqrtm(sqrtm(op0) @ op1 @ sqrtm(op0)))) ** 2) fid = min(fid, 1.0) fid = max(fid, 0.0) # Correct for rounding errors return fid
Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend.
def bures_angle(rho0: Density, rho1: Density) -> float: """Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend. """ return np.arccos(np.sqrt(fidelity(rho0, rho1)))
Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend.
def bures_distance(rho0: Density, rho1: Density) -> float: """Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend. """ fid = fidelity(rho0, rho1) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) tr0 = np.trace(op0) tr1 = np.trace(op1) return np.sqrt(tr0 + tr1 - 2.*np.sqrt(fid))
The Fubini-Study angle between density matrices
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor: """The Fubini-Study angle between density matrices""" return fubini_study_angle(rho0.vec, rho1.vec)
Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle.
def densities_close(rho0: Density, rho1: Density, tolerance: float = TOLERANCE) -> bool: """Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(rho0.vec, rho1.vec, tolerance)
Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho
def entropy(rho: Density, base: float = None) -> float: """ Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho """ op = asarray(rho.asoperator()) probs = np.linalg.eigvalsh(op) probs = np.maximum(probs, 0.0) # Compensate for floating point errors return scipy.stats.entropy(probs, base=base)
Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information.
def mutual_info(rho: Density, qubits0: Qubits, qubits1: Qubits = None, base: float = None) -> float: """Compute the bipartite von-Neumann mutual information of a mixed quantum state. Args: rho: A density matrix of the complete system qubits0: Qubits of system 0 qubits1: Qubits of system 1. If none, taken to be all remaining qubits base: Optional logarithm base. Default is base e Returns: The bipartite von-Neumann mutual information. """ if qubits1 is None: qubits1 = tuple(set(rho.qubits) - set(qubits0)) rho0 = rho.partial_trace(qubits1) rho1 = rho.partial_trace(qubits0) ent = entropy(rho, base) ent0 = entropy(rho0, base) ent1 = entropy(rho1, base) return ent0 + ent1 - ent
The Fubini-Study angle between gates
def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor: """The Fubini-Study angle between gates""" return fubini_study_angle(gate0.vec, gate1.vec)
Returns: True if gates are almost identical. Closeness is measured with the gate angle.
def gates_close(gate0: Gate, gate1: Gate, tolerance: float = TOLERANCE) -> bool: """Returns: True if gates are almost identical. Closeness is measured with the gate angle. """ return vectors_close(gate0.vec, gate1.vec, tolerance)
The Fubini-Study angle between channels
def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor: """The Fubini-Study angle between channels""" return fubini_study_angle(chan0.vec, chan1.vec)
Returns: True if channels are almost identical. Closeness is measured with the channel angle.
def channels_close(chan0: Channel, chan1: Channel, tolerance: float = TOLERANCE) -> bool: """Returns: True if channels are almost identical. Closeness is measured with the channel angle. """ return vectors_close(chan0.vec, chan1.vec, tolerance)
Return the diamond norm between two completely positive trace-preserving (CPTP) superoperators. The calculation uses the simplified semidefinite program of Watrous [arXiv:0901.4709](http://arxiv.org/abs/0901.4709) [J. Watrous, [Theory of Computing 5, 11, pp. 217-238 (2009)](http://theoryofcomputing.org/articles/v005a011/)]
def diamond_norm(chan0: Channel, chan1: Channel) -> float: """Return the diamond norm between two completely positive trace-preserving (CPTP) superoperators. The calculation uses the simplified semidefinite program of Watrous [arXiv:0901.4709](http://arxiv.org/abs/0901.4709) [J. Watrous, [Theory of Computing 5, 11, pp. 217-238 (2009)](http://theoryofcomputing.org/articles/v005a011/)] """ # Kudos: Based on MatLab code written by Marcus P. da Silva # (https://github.com/BBN-Q/matlab-diamond-norm/) if set(chan0.qubits) != set(chan1.qubits): raise ValueError('Channels must operate on same qubits') if chan0.qubits != chan1.qubits: chan1 = chan1.permute(chan0.qubits) N = chan0.qubit_nb dim = 2**N choi0 = asarray(chan0.choi()) choi1 = asarray(chan1.choi()) delta_choi = choi0 - choi1 # Density matrix must be Hermitian, positive semidefinite, trace 1 rho = cvx.Variable([dim, dim], complex=True) constraints = [rho == rho.H] constraints += [rho >> 0] constraints += [cvx.trace(rho) == 1] # W must be Hermitian, positive semidefinite W = cvx.Variable([dim**2, dim**2], complex=True) constraints += [W == W.H] constraints += [W >> 0] constraints += [(W - cvx.kron(np.eye(dim), rho)) << 0] J = cvx.Parameter([dim**2, dim**2], complex=True) objective = cvx.Maximize(cvx.real(cvx.trace(J.H * W))) prob = cvx.Problem(objective, constraints) J.value = delta_choi prob.solve() dnorm = prob.value * 2 # Diamond norm is between 0 and 2. Correct for floating point errors dnorm = min(2, dnorm) dnorm = max(0, dnorm) return dnorm
Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match.
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must match') vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order return bk.inner(vec0.tensor, vec1.tensor)
Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint.
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. """ R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly vectors. Rank must match') if not set(vec0.qubits).isdisjoint(vec1.qubits): raise ValueError('Overlapping qubits') qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits) tensor = bk.outer(vec0.tensor, vec1.tensor) # Interleave (super)-operator axes # R = 1 perm = (0, 1) # R = 2 perm = (0, 2, 1, 3) # R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7) tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R)) perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij] tensor = bk.transpose(tensor, perm) return QubitVector(tensor, qubits)
Calculate the Fubini–Study metric between elements of a Hilbert space. The Fubini–Study metric is a distance measure between vectors in a projective Hilbert space. For gates this space is the Hilbert space of operators induced by the Hilbert-Schmidt inner product. For 1-qubit rotation gates, RX, RY and RZ, this is half the angle (theta) in the Bloch sphere. The Fubini–Study metric between states is equal to the Burr angle between pure states.
def fubini_study_angle(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """Calculate the Fubini–Study metric between elements of a Hilbert space. The Fubini–Study metric is a distance measure between vectors in a projective Hilbert space. For gates this space is the Hilbert space of operators induced by the Hilbert-Schmidt inner product. For 1-qubit rotation gates, RX, RY and RZ, this is half the angle (theta) in the Bloch sphere. The Fubini–Study metric between states is equal to the Burr angle between pure states. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must match') vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order t0 = vec0.tensor t1 = vec1.tensor hs01 = bk.inner(t0, t1) # Hilbert-Schmidt inner product hs00 = bk.inner(t0, t0) hs11 = bk.inner(t1, t1) ratio = bk.absolute(hs01) / bk.sqrt(bk.absolute(hs00*hs11)) ratio = bk.minimum(ratio, bk.fcast(1.)) # Compensate for rounding errors. return bk.arccos(ratio)
Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric.
def vectors_close(vec0: QubitVector, vec1: QubitVector, tolerance: float = TOLERANCE) -> bool: """Return True if vectors in close in the projective Hilbert space. Similarity is measured with the Fubini–Study metric. """ if vec0.rank != vec1.rank: return False if vec0.qubit_nb != vec1.qubit_nb: return False if set(vec0.qubits) ^ set(vec1.qubits): return False return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance
Utility method for unraveling 'qubits: Union[int, Qubits]' arguments
def qubits_count_tuple(qubits: Union[int, Qubits]) -> Tuple[int, Qubits]: """Utility method for unraveling 'qubits: Union[int, Qubits]' arguments""" if isinstance(qubits, int): return qubits, tuple(range(qubits)) return len(qubits), qubits
Return tensor with with qubit indices flattened
def flatten(self) -> bk.BKTensor: """Return tensor with with qubit indices flattened""" N = self.qubit_nb R = self.rank return bk.reshape(self.tensor, [2**N]*R)
Return a copy of this vector with new qubits
def relabel(self, qubits: Qubits) -> 'QubitVector': """Return a copy of this vector with new qubits""" qubits = tuple(qubits) assert len(qubits) == self.qubit_nb vec = copy(self) vec.qubits = qubits return vec
Permute the order of the qubits
def permute(self, qubits: Qubits) -> 'QubitVector': """Permute the order of the qubits""" if qubits == self.qubits: return self N = self.qubit_nb assert len(qubits) == N # Will raise a value error if qubits don't match indices = [self.qubits.index(q) for q in qubits] # type: ignore perm: List[int] = [] for rr in range(0, self.rank): perm += [rr * N + idx for idx in indices] tensor = bk.transpose(self.tensor, perm) return QubitVector(tensor, qubits)
Return the conjugate transpose of this tensor.
def H(self) -> 'QubitVector': """Return the conjugate transpose of this tensor.""" N = self.qubit_nb R = self.rank # (super) operator transpose tensor = self.tensor tensor = bk.reshape(tensor, [2**(N*R//2)] * 2) tensor = bk.transpose(tensor) tensor = bk.reshape(tensor, [2] * R * N) tensor = bk.conj(tensor) return QubitVector(tensor, self.qubits)
Return the norm of this vector
def norm(self) -> bk.BKTensor: """Return the norm of this vector""" return bk.absolute(bk.inner(self.tensor, self.tensor))
Return the trace, the sum of the diagonal elements of the (super) operator.
def trace(self) -> bk.BKTensor: """ Return the trace, the sum of the diagonal elements of the (super) operator. """ N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') tensor = bk.reshape(self.tensor, [2**(N*R//2)] * 2) tensor = bk.trace(tensor) return tensor
Return the partial trace over some subset of qubits
def partial_trace(self, qubits: Qubits) -> 'QubitVector': """ Return the partial trace over some subset of qubits""" N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) for q in qubits: new_qubits.remove(q) if not new_qubits: raise ValueError('Cannot remove all qubits with partial_trace.') indices = [self.qubits.index(qubit) for qubit in qubits] subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R] for idx in indices: for r in range(1, R): subscripts[r * N + idx] = subscripts[idx] subscript_str = ''.join(subscripts) # Only numpy's einsum works with repeated subscripts tensor = self.asarray() tensor = np.einsum(subscript_str, tensor) return QubitVector(tensor, new_qubits)
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
def fit_zyz(target_gate): """ Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ steps = 1000 dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0' with tf.device(dev): t = tf.Variable(tf.random.normal([3])) def loss_fn(): """Loss""" gate = qf.ZYZ(t[0], t[1], t[2]) ang = qf.fubini_study_angle(target_gate.vec, gate.vec) return ang opt = tf.optimizers.Adam(learning_rate=0.001) opt.minimize(loss_fn, var_list=[t]) for step in range(steps): opt.minimize(loss_fn, var_list=[t]) loss = loss_fn() print(step, loss.numpy()) if loss < 0.01: break else: print("Failed to coverge") return bk.evaluate(t)
Initialize program state. Called by program.run() and .evolve()
def _initilize(self, state: State) -> State: """Initialize program state. Called by program.run() and .evolve()""" targets = {} for pc, instr in enumerate(self): if isinstance(instr, Label): targets[instr.target] = pc state = state.update({PC: 0, TARGETS: targets, NAMEDGATES: STDGATES.copy()}) return state
Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states.
def run(self, ket: State = None) -> State: """Compiles and runs a program. The optional program argument supplies the initial state and memory. Else qubits and classical bits start from zero states. """ if ket is None: qubits = self.qubits ket = zero_state(qubits) ket = self._initilize(ket) pc = 0 while pc >= 0 and pc < len(self): instr = self.instructions[pc] ket = ket.update({PC: pc + 1}) ket = instr.run(ket) pc = ket.memory[PC] return ket
Return a copy of this Gate with new qubits
def relabel(self, qubits: Qubits) -> 'Gate': """Return a copy of this Gate with new qubits""" gate = copy(self) gate.vec = gate.vec.relabel(qubits) return gate
Permute the order of the qubits
def permute(self, qubits: Qubits) -> 'Gate': """Permute the order of the qubits""" vec = self.vec.permute(qubits) return Gate(vec.tensor, qubits=vec.qubits)
Apply the action of this gate upon a state
def run(self, ket: State) -> State: """Apply the action of this gate upon a state""" qubits = self.qubits indices = [ket.qubits.index(q) for q in qubits] tensor = bk.tensormul(self.tensor, ket.tensor, indices) return State(tensor, ket.qubits, ket.memory)
Apply the action of this gate upon a density
def evolve(self, rho: Density) -> Density: """Apply the action of this gate upon a density""" # TODO: implement without explicit channel creation? chan = self.aschannel() return chan.evolve(rho)
Converts a Gate into a Channel
def aschannel(self) -> 'Channel': """Converts a Gate into a Channel""" N = self.qubit_nb R = 4 tensor = bk.outer(self.tensor, self.H.tensor) tensor = bk.reshape(tensor, [2**N]*R) tensor = bk.transpose(tensor, [0, 3, 1, 2]) return Channel(tensor, self.qubits)
Convert gate tensor to the special unitary group.
def su(self) -> 'Gate': """Convert gate tensor to the special unitary group.""" rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(U) ** (1/rank) return Gate(tensor=U, qubits=self.qubits)
Return a copy of this channel with new qubits
def relabel(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with new qubits""" chan = copy(self) chan.vec = chan.vec.relabel(qubits) return chan
Return a copy of this channel with qubits in new order
def permute(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with qubits in new order""" vec = self.vec.permute(qubits) return Channel(vec.tensor, qubits=vec.qubits)
r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi())
def sharp(self) -> 'Channel': r"""Return the 'sharp' transpose of the superoperator. The transpose :math:`S^\#` switches the two covariant (bra) indices of the superoperator. (Which in our representation are the 2nd and 3rd super-indices) If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map (i.e. transforms Hermitian operators to hJrmitian operators) Flattening the :math:`S^\#` superoperator to a matrix gives the Choi matrix representation. (See channel.choi()) """ N = self.qubit_nb tensor = self.tensor tensor = bk.reshape(tensor, [2**N] * 4) tensor = bk.transpose(tensor, (0, 2, 1, 3)) tensor = bk.reshape(tensor, [2] * 4 * N) return Channel(tensor, self.qubits)
Return the Choi matrix representation of this super operator
def choi(self) -> bk.BKTensor: """Return the Choi matrix representation of this super operator""" # Put superop axes in [ok, ib, ob, ik] and reshape to matrix N = self.qubit_nb return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2)
Apply the action of this channel upon a density
def evolve(self, rho: Density) -> Density: """Apply the action of this channel upon a density""" N = rho.qubit_nb qubits = rho.qubits indices = list([qubits.index(q) for q in self.qubits]) + \ list([qubits.index(q) + N for q in self.qubits]) tensor = bk.tensormul(self.tensor, rho.tensor, indices) return Density(tensor, qubits, rho.memory)
Return the partial trace over the specified qubits
def partial_trace(self, qubits: Qubits) -> 'Channel': """Return the partial trace over the specified qubits""" vec = self.vec.partial_trace(qubits) return Channel(vec.tensor, vec.qubits)
Cast to float tensor
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
Convert to product tensor
def astensor(array: TensorLike) -> BKTensor: """Convert to product tensor""" tensor = tf.convert_to_tensor(array, dtype=CTYPE) if DEVICE == 'gpu': tensor = tensor.gpu() # pragma: no cover # size = np.prod(np.array(tensor.get_shape().as_list())) N = int(math.log2(size(tensor))) tensor = tf.reshape(tensor, ([2]*N)) return tensor
Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit
def count_operations(elements: Iterable[Operation]) \ -> Dict[Type[Operation], int]: """Return a count of different operation types given a colelction of operations, such as a Circuit or DAGCircuit """ op_count: Dict[Type[Operation], int] = defaultdict(int) for elem in elements: op_count[type(elem)] += 1 return dict(op_count)
Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2)
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: """Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2) """ circ = Circuit() for qubits in args: circ += gate.relabel(qubits) return circ
Returns the Quantum Fourier Transform circuit
def qft_circuit(qubits: Qubits) -> Circuit: """Returns the Quantum Fourier Transform circuit""" # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py N = len(qubits) circ = Circuit() for n0 in range(N): q0 = qubits[n0] circ += H(q0) for n1 in range(n0+1, N): q1 = qubits[n1] angle = pi / 2 ** (n1-n0) circ += CPHASE(angle, q1, q0) circ.extend(reversal_circuit(qubits)) return circ
Returns a circuit to reverse qubits
def reversal_circuit(qubits: Qubits) -> Circuit: """Returns a circuit to reverse qubits""" N = len(qubits) circ = Circuit() for n in range(N // 2): circ += SWAP(qubits[n], qubits[N-1-n]) return circ
Returns a circuit for a target gate controlled by a collection of control qubits. [Barenco1995]_ Uses a number of gates quadratic in the number of control qubits. .. [Barenco1995] A. Barenco, C. Bennett, R. Cleve (1995) Elementary Gates for Quantum Computation`<https://arxiv.org/abs/quant-ph/9503016>`_ Sec 7.2
def control_circuit(controls: Qubits, gate: Gate) -> Circuit: """ Returns a circuit for a target gate controlled by a collection of control qubits. [Barenco1995]_ Uses a number of gates quadratic in the number of control qubits. .. [Barenco1995] A. Barenco, C. Bennett, R. Cleve (1995) Elementary Gates for Quantum Computation`<https://arxiv.org/abs/quant-ph/9503016>`_ Sec 7.2 """ # Kudos: Adapted from Rigetti Grove's utility_programs.py # grove/utils/utility_programs.py::ControlledProgramBuilder circ = Circuit() if len(controls) == 1: q0 = controls[0] if isinstance(gate, X): circ += CNOT(q0, gate.qubits[0]) else: cgate = control_gate(q0, gate) circ += cgate else: circ += control_circuit(controls[-1:], gate ** 0.5) circ += control_circuit(controls[0:-1], X(controls[-1])) circ += control_circuit(controls[-1:], gate ** -0.5) circ += control_circuit(controls[0:-1], X(controls[-1])) circ += control_circuit(controls[0:-1], gate ** 0.5) return circ
Standard decomposition of CCNOT (Toffoli) gate into six CNOT gates (Plus Hadamard and T gates.) [Nielsen2000]_ .. [Nielsen2000] M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, Cambridge University Press (2000).
def ccnot_circuit(qubits: Qubits) -> Circuit: """Standard decomposition of CCNOT (Toffoli) gate into six CNOT gates (Plus Hadamard and T gates.) [Nielsen2000]_ .. [Nielsen2000] M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, Cambridge University Press (2000). """ if len(qubits) != 3: raise ValueError('Expected 3 qubits') q0, q1, q2 = qubits circ = Circuit() circ += H(q2) circ += CNOT(q1, q2) circ += T(q2).H circ += CNOT(q0, q2) circ += T(q2) circ += CNOT(q1, q2) circ += T(q2).H circ += CNOT(q0, q2) circ += T(q1) circ += T(q2) circ += H(q2) circ += CNOT(q0, q1) circ += T(q0) circ += T(q1).H circ += CNOT(q0, q1) return circ
Circuit equivalent of 1-qubit ZYZ gate
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit: """Circuit equivalent of 1-qubit ZYZ gate""" circ = Circuit() circ += TZ(t0, q0) circ += TY(t1, q0) circ += TZ(t2, q0) return circ
Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25
def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit: """Returns a circuit for quantum phase estimation. The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To run the circuit, the eigenvector should be set on the gate qubits, and the output qubits should be in the zero state. After evolution and measurement, the output qubits will be (approximately) a binary fraction representation of the phase. The output registers can be converted with the aid of the quantumflow.utils.bitlist_to_int() method. >>> import numpy as np >>> import quantumflow as qf >>> N = 8 >>> phase = 1/4 >>> gate = qf.RZ(-4*np.pi*phase, N) >>> circ = qf.phase_estimation_circuit(gate, range(N)) >>> res = circ.run().measure()[0:N] >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float >>> print(phase, est_phase) 0.25 0.25 """ circ = Circuit() circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits for cq in reversed(outputs): cgate = control_gate(cq, gate) circ += cgate gate = gate @ gate circ += qft_circuit(outputs).H return circ
Returns a quantum circuit for ripple-carry addition. [Cuccaro2004]_ Requires two carry qubit (input and output). The result is returned in addend1. .. [Cuccaro2004] A new quantum ripple-carry addition circuit, Steven A. Cuccaro, Thomas G. Draper, Samuel A. Kutin, David Petrie Moulton arXiv:quant-ph/0410184 (2004)
def addition_circuit( addend0: Qubits, addend1: Qubits, carry: Qubits) -> Circuit: """Returns a quantum circuit for ripple-carry addition. [Cuccaro2004]_ Requires two carry qubit (input and output). The result is returned in addend1. .. [Cuccaro2004] A new quantum ripple-carry addition circuit, Steven A. Cuccaro, Thomas G. Draper, Samuel A. Kutin, David Petrie Moulton arXiv:quant-ph/0410184 (2004) """ if len(addend0) != len(addend1): raise ValueError('Number of addend qubits must be equal') if len(carry) != 2: raise ValueError('Expected 2 carry qubits') def _maj(qubits: Qubits) -> Circuit: q0, q1, q2 = qubits circ = Circuit() circ += CNOT(q2, q1) circ += CNOT(q2, q0) circ += CCNOT(q0, q1, q2) return circ def _uma(qubits: Qubits) -> Circuit: q0, q1, q2 = qubits circ = Circuit() circ += CCNOT(q0, q1, q2) circ += CNOT(q2, q0) circ += CNOT(q0, q1) return circ qubits = [carry[0]] + list(chain.from_iterable( zip(reversed(addend1), reversed(addend0)))) + [carry[1]] circ = Circuit() for n in range(0, len(qubits)-3, 2): circ += _maj(qubits[n:n+3]) circ += CNOT(qubits[-2], qubits[-1]) for n in reversed(range(0, len(qubits)-3, 2)): circ += _uma(qubits[n:n+3]) return circ
Returns a circuit that prepares a multi-qubit Bell state from the zero state.
def ghz_circuit(qubits: Qubits) -> Circuit: """Returns a circuit that prepares a multi-qubit Bell state from the zero state. """ circ = Circuit() circ += H(qubits[0]) for q0 in range(0, len(qubits)-1): circ += CNOT(qubits[q0], qubits[q0+1]) return circ
Append gates from circuit to the end of this circuit
def extend(self, other: Operation) -> None: """Append gates from circuit to the end of this circuit""" if isinstance(other, Circuit): self.elements.extend(other.elements) else: self.elements.extend([other])
Returns: Sorted list of qubits acted upon by this circuit Raises: TypeError: If qubits cannot be sorted into unique order.
def qubits(self) -> Qubits: """Returns: Sorted list of qubits acted upon by this circuit Raises: TypeError: If qubits cannot be sorted into unique order. """ qbs = [q for elem in self.elements for q in elem.qubits] # gather qbs = list(set(qbs)) # unique qbs = sorted(qbs) # sort return tuple(qbs)
Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created.
def run(self, ket: State = None) -> State: """ Apply the action of this circuit upon a state. If no initial state provided an initial zero state will be created. """ if ket is None: qubits = self.qubits ket = zero_state(qubits=qubits) for elem in self.elements: ket = elem.run(ket) return ket
Return the action of this circuit as a gate
def asgate(self) -> Gate: """ Return the action of this circuit as a gate """ gate = identity_gate(self.qubits) for elem in self.elements: gate = elem.asgate() @ gate return gate
Join two channels acting on different qubits into a single channel acting on all qubits
def join_channels(*channels: Channel) -> Channel: """Join two channels acting on different qubits into a single channel acting on all qubits""" vectors = [chan.vec for chan in channels] vec = reduce(outer_product, vectors) return Channel(vec.tensor, vec.qubits)
Convert a channel superoperator into a Kraus operator representation of the same channel.
def channel_to_kraus(chan: Channel) -> 'Kraus': """Convert a channel superoperator into a Kraus operator representation of the same channel.""" qubits = chan.qubits N = chan.qubit_nb choi = asarray(chan.choi()) evals, evecs = np.linalg.eig(choi) evecs = np.transpose(evecs) assert np.allclose(evals.imag, 0.0) # FIXME exception assert np.all(evals.real >= 0.0) # FIXME exception values = np.sqrt(evals.real) ops = [] for i in range(2**(2*N)): if not np.isclose(values[i], 0.0): mat = np.reshape(evecs[i], (2**N, 2**N))*values[i] g = Gate(mat, qubits) ops.append(g) return Kraus(ops)
Returns True if the collection of (weighted) Kraus operators are complete. (Which is necessary for a CPTP map to preserve trace)
def kraus_iscomplete(kraus: Kraus) -> bool: """Returns True if the collection of (weighted) Kraus operators are complete. (Which is necessary for a CPTP map to preserve trace) """ qubits = kraus.qubits N = kraus.qubit_nb ident = Gate(np.eye(2**N), qubits) # FIXME tensors = [(op.H @ op @ ident).asoperator() for op in kraus.operators] tensors = [t*w for t, w in zip(tensors, kraus.weights)] tensor = reduce(np.add, tensors) res = Gate(tensor, qubits) return almost_identity(res)
Returns: Action of Kraus operators as a superoperator Channel
def aschannel(self) -> Channel: """Returns: Action of Kraus operators as a superoperator Channel""" qubits = self.qubits N = len(qubits) ident = Gate(np.eye(2**N), qubits=qubits).aschannel() channels = [op.aschannel() @ ident for op in self.operators] if self.weights is not None: channels = [c*w for c, w in zip(channels, self.weights)] channel = reduce(add, channels) return channel
Apply the action of this Kraus quantum operation upon a state
def run(self, ket: State) -> State: """Apply the action of this Kraus quantum operation upon a state""" res = [op.run(ket) for op in self.operators] probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)] probs = np.asarray(probs) probs /= np.sum(probs) newket = np.random.choice(res, p=probs) return newket.normalize()
Apply the action of this Kraus quantum operation upon a density
def evolve(self, rho: Density) -> Density: """Apply the action of this Kraus quantum operation upon a density""" qubits = rho.qubits results = [op.evolve(rho) for op in self.operators] tensors = [rho.tensor * w for rho, w in zip(results, self.weights)] tensor = reduce(add, tensors) return Density(tensor, qubits)
Return the complex conjugate of this Kraus operation
def H(self) -> 'Kraus': """Return the complex conjugate of this Kraus operation""" operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
Return one of the composite Kraus operators at random with the appropriate weights
def asgate(self) -> Gate: """Return one of the composite Kraus operators at random with the appropriate weights""" return np.random.choice(self.operators, p=self.weights)
Create an image of a quantum circuit in LaTeX. Can currently draw X, Y, Z, H, T, S, T_H, S_H, RX, RY, RZ, TX, TY, TZ, TH, CNOT, CZ, SWAP, ISWAP, CCNOT, CSWAP, XX, YY, ZZ, CAN, P0 and P1 gates, and the RESET operation. Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order document: If false, just the qcircuit latex is returned. Else the circuit image is wrapped in a standalone LaTeX document ready for typesetting. Returns: A LaTeX string representation of the circuit. Raises: NotImplementedError: For unsupported gates. Refs: LaTeX Qcircuit package (https://arxiv.org/pdf/quant-ph/0406003).
def circuit_to_latex(circ: Circuit, qubits: Qubits = None, document: bool = True) -> str: """ Create an image of a quantum circuit in LaTeX. Can currently draw X, Y, Z, H, T, S, T_H, S_H, RX, RY, RZ, TX, TY, TZ, TH, CNOT, CZ, SWAP, ISWAP, CCNOT, CSWAP, XX, YY, ZZ, CAN, P0 and P1 gates, and the RESET operation. Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order document: If false, just the qcircuit latex is returned. Else the circuit image is wrapped in a standalone LaTeX document ready for typesetting. Returns: A LaTeX string representation of the circuit. Raises: NotImplementedError: For unsupported gates. Refs: LaTeX Qcircuit package (https://arxiv.org/pdf/quant-ph/0406003). """ if qubits is None: qubits = circ.qubits N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) layers = _display_layers(circ, qubits) layer_code = [] code = [r'\lstick{' + str(q) + r'}' for q in qubits] layer_code.append(code) def _two_qubit_gate(top, bot, label): if bot-top == 1: code_top = r'\multigate{1}{%s}' % label code_bot = r'\ghost{%s}' % label else: code_top = r'\sgate{%s}{%s}' % (label, str(bot - top)) code_bot = r'\gate{%s}' % (label) return code_top, code_bot for layer in layers.elements: code = [r'\qw'] * N assert isinstance(layer, Circuit) for gate in layer: idx = [qubit_idx[q] for q in gate.qubits] name = gate.name if isinstance(gate, I): pass elif(len(idx) == 1) and name in ['X', 'Y', 'Z', 'H', 'T', 'S']: code[idx[0]] = r'\gate{' + gate.name + '}' elif isinstance(gate, S_H): code[idx[0]] = r'\gate{S^\dag}' elif isinstance(gate, T_H): code[idx[0]] = r'\gate{T^\dag}' elif isinstance(gate, RX): theta = _latex_format(gate.params['theta']) code[idx[0]] = r'\gate{R_x(%s)}' % theta elif isinstance(gate, RY): theta = _latex_format(gate.params['theta']) code[idx[0]] = r'\gate{R_y(%s)}' % theta elif isinstance(gate, RZ): theta = _latex_format(gate.params['theta']) code[idx[0]] = r'\gate{R_z(%s)}' % theta elif isinstance(gate, TX): t = _latex_format(gate.params['t']) code[idx[0]] = r'\gate{X^{%s}}' % t elif isinstance(gate, TY): t = _latex_format(gate.params['t']) code[idx[0]] = r'\gate{Y^{%s}}' % t elif isinstance(gate, TZ): t = _latex_format(gate.params['t']) code[idx[0]] = r'\gate{Z^{%s}}' % t elif isinstance(gate, TH): t = _latex_format(gate.params['t']) code[idx[0]] = r'\gate{H^{%s}}' % t elif isinstance(gate, CNOT): code[idx[0]] = r'\ctrl{' + str(idx[1] - idx[0]) + '}' code[idx[1]] = r'\targ' elif isinstance(gate, XX): label = r'X\!X^{%s}' % _latex_format(gate.params['t']) top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, YY): label = r'Y\!Y^{%s}' % _latex_format(gate.params['t']) top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, ZZ): label = r'Z\!Z^{%s}' % _latex_format(gate.params['t']) top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, CPHASE): theta = _latex_format(gate.params['theta']) label = r'\text{CPHASE}({%s})' % theta top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, PSWAP): theta = _latex_format(gate.params['theta']) label = r'\text{PSWAP}({%s})' % theta top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, CZ): code[idx[0]] = r'\ctrl{' + str(idx[1] - idx[0]) + '}' code[idx[1]] = r'\ctrl{' + str(idx[0] - idx[1]) + '}' elif isinstance(gate, SWAP): code[idx[0]] = r'\qswap \qwx[' + str(idx[1] - idx[0]) + ']' code[idx[1]] = r'\qswap' elif isinstance(gate, CAN): tx = _latex_format(gate.params['tx']) ty = _latex_format(gate.params['ty']) tz = _latex_format(gate.params['tz']) label = r'{\text{CAN}(%s, %s, %s)}' % (tx, ty, tz) top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, ISWAP): label = r'{ \text{iSWAP}}' top = min(idx) bot = max(idx) code[top], code[bot] = _two_qubit_gate(top, bot, label) elif isinstance(gate, CCNOT): code[idx[0]] = r'\ctrl{' + str(idx[1]-idx[0]) + '}' code[idx[1]] = r'\ctrl{' + str(idx[2]-idx[1]) + '}' code[idx[2]] = r'\targ' elif isinstance(gate, CSWAP): code[idx[0]] = r'\ctrl{' + str(idx[1]-idx[0]) + '}' code[idx[1]] = r'\qswap \qwx[' + str(idx[2] - idx[1]) + ']' code[idx[2]] = r'\qswap' elif isinstance(gate, P0): code[idx[0]] = r'\push{\ket{0}\!\!\bra{0}} \qw' elif isinstance(gate, P1): code[idx[0]] = r'\push{\ket{1}\!\!\bra{1}} \qw' elif isinstance(gate, Reset): for i in idx: code[i] = r'\push{\rule{0.1em}{0.5em}\, \ket{0}\,} \qw' elif isinstance(gate, Measure): code[idx[0]] = r'\meter' else: raise NotImplementedError(str(gate)) layer_code.append(code) code = [r'\qw'] * N layer_code.append(code) latex_lines = [''] * N for line, wire in enumerate(zip(*layer_code)): latex = '& ' + ' & '.join(wire) if line < N - 1: # Not last line latex += r' \\' latex_lines[line] = latex latex_code = _QCIRCUIT % '\n'.join(latex_lines) if document: latex_code = _DOCUMENT_HEADER + latex_code + _DOCUMENT_FOOTER return latex_code
Separate a circuit into groups of gates that do not visually overlap
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) unused = [True] * N for gl in gate_layers: assert isinstance(gl, Circuit) for gate in gl: indices = [qubit_idx[q] for q in gate.qubits] if not all(unused[min(indices):max(indices)+1]): # New layer lcirc = Circuit() layers.append(lcirc) unused = [True] * N unused[min(indices):max(indices)+1] = \ [False] * (max(indices) - min(indices) + 1) lcirc += gate return Circuit(layers)