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.iden...
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:110...
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(ele...
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 ...
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...
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,...
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)) ...
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'...
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)) retu...
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 ...
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 ...
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...
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...
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 [] ...
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 isinst...
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: ...
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]) ...
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._pr...
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 ...
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...
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...
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 = ...
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 participat...
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 ...
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...
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...
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: ...
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 bas...
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 qubits...
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...
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...
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 ma...
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...
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...
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 indu...
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.qubi...
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 ...
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.r...
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*...
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) ...
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.r...
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, ...
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...
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....
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 :mat...
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(se...
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 =...
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_c...
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)...
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): ...
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/95030...
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 G...
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). ...
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 (approximatel...
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....
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 ...
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 rippl...
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)) ...
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...
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.al...
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 @ i...
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 ...
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) new...
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, tensor...
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 ...
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, ...
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) un...