for next_node in self.topological_op_nodes():<EOL><INDENT>new_layer = DAGCircuit()<EOL>for qreg in self.qregs.values():<EOL><INDENT>new_layer.add_qreg(qreg)<EOL><DEDENT>for creg in self.cregs.values():<EOL><INDENT>new_layer.add_creg(creg)<EOL><DEDENT>support_list = []<EOL>op = copy.copy(next_node.op)<EOL>qa = copy.copy(next_node.qargs)<EOL>ca = copy.copy(next_node.cargs)<EOL>co = copy.copy(next_node.condition)<EOL>_ = self._bits_in_condition(co)<EOL>new_layer.apply_operation_back(op, qa, ca, co)<EOL>if next_node.name not in ["<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>support_list.append(list(qa))<EOL><DEDENT>l_dict = {"<STR_LIT>": new_layer, "<STR_LIT>": support_list}<EOL>yield l_dict<EOL><DEDENT>

Yield a layer for all gates of this circuit.

        A serial layer is a circuit with one gate. The layers have the
        same structure as in layers().


return nx.number_weakly_connected_components(self._multi_graph)<EOL>

Compute how many components the circuit can decompose into.


warnings.warn('<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>named_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and node.op.name in names:<EOL><INDENT>named_nodes.append(node._node_id)<EOL><DEDENT><DEDENT>return named_nodes<EOL>


def substitute_node_with_dag(self, node, input_dag, wires=None):

if isinstance(node, int):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>node = self._id_to_node[node]<EOL><DEDENT>condition = node.condition<EOL>if condition:<EOL><INDENT>input_dag.add_creg(condition[<NUM_LIT:0>])<EOL>to_replay = []<EOL>for sorted_node in input_dag.topological_nodes():<EOL><INDENT>if sorted_node.type == "<STR_LIT>":<EOL><INDENT>sorted_node.op.control = condition<EOL>to_replay.append(sorted_node)<EOL><DEDENT><DEDENT>for input_node in input_dag.op_nodes():<EOL><INDENT>input_dag.remove_op_node(input_node)<EOL><DEDENT>for replay_node in to_replay:<EOL><INDENT>input_dag.apply_operation_back(replay_node.op, replay_node.qargs,<EOL>replay_node.cargs, condition=condition)<EOL><DEDENT><DEDENT>if wires is None:<EOL><INDENT>qwires = [w for w in input_dag.wires if isinstance(w[<NUM_LIT:0>], QuantumRegister)]<EOL>cwires = [w for w in input_dag.wires if isinstance(w[<NUM_LIT:0>], ClassicalRegister)]<EOL>wires = qwires + cwires<EOL><DEDENT>self._check_wires_list(wires, node)<EOL>proxy_map = {w: QuantumRegister(<NUM_LIT:1>, '<STR_LIT>') for w in wires}<EOL>add_qregs = self._check_edgemap_registers(proxy_map,<EOL>input_dag.qregs,<EOL>{}, False)<EOL>for qreg in add_qregs:<EOL><INDENT>self.add_qreg(qreg)<EOL><DEDENT>add_cregs = self._check_edgemap_registers(proxy_map,<EOL>input_dag.cregs,<EOL>{}, False)<EOL>for creg in add_cregs:<EOL><INDENT>self.add_creg(creg)<EOL><DEDENT>if node.type != "<STR_LIT>":<EOL><INDENT>raise DAGCircuitError("<STR_LIT>"<EOL>% node.type)<EOL><DEDENT>condition_bit_list = self._bits_in_condition(node.condition)<EOL>wire_map = {k: v for k, v in zip(wires,<EOL>[i for s in [node.qargs,<EOL>node.cargs,<EOL>condition_bit_list]<EOL>for i in s])}<EOL>self._check_wiremap_validity(wire_map, wires, self.input_map)<EOL>pred_map, succ_map = self._make_pred_succ_maps(node)<EOL>full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,<EOL>input_dag, wire_map)<EOL>self._multi_graph.remove_node(node)<EOL>for sorted_node in input_dag.topological_op_nodes():<EOL><INDENT>condition = self._map_condition(wire_map, sorted_node.condition)<EOL>m_qargs = list(map(lambda x: wire_map.get(x, x),<EOL>sorted_node.qargs))<EOL>m_cargs = list(map(lambda x: wire_map.get(x, x),<EOL>sorted_node.cargs))<EOL>self._add_op_node(sorted_node.op, m_qargs, m_cargs, condition)<EOL>all_cbits = self._bits_in_condition(condition)<EOL>all_cbits.extend(m_cargs)<EOL>al = [m_qargs, all_cbits]<EOL>for q in itertools.chain(*al):<EOL><INDENT>self._multi_graph.add_edge(full_pred_map[q],<EOL>self._id_to_node[self._max_node_id],<EOL>name="<STR_LIT>" % (q[<NUM_LIT:0>].name, q[<NUM_LIT:1>]),<EOL>wire=q)<EOL>full_pred_map[q] = self._id_to_node[self._max_node_id]<EOL><DEDENT><DEDENT>for w in full_pred_map:<EOL><INDENT>self._multi_graph.add_edge(full_pred_map[w],<EOL>full_succ_map[w],<EOL>name="<STR_LIT>" % (w[<NUM_LIT:0>].name, w[<NUM_LIT:1>]),<EOL>wire=w)<EOL>o_pred = list(self._multi_graph.predecessors(self.output_map[w]))<EOL>if len(o_pred) > <NUM_LIT:1>:<EOL><INDENT>if len(o_pred) != <NUM_LIT:2>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>p = [x for x in o_pred if x != full_pred_map[w]]<EOL>if len(p) != <NUM_LIT:1>:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>self._multi_graph.remove_edge(p[<NUM_LIT:0>], self.output_map[w])<EOL><DEDENT><DEDENT>

Replace one node with dag.

        Args:
            node (DAGNode): node to substitute
            input_dag (DAGCircuit): circuit that will substitute the node
            wires (list[(Register, index)]): gives an order for (qu)bits
                in the input circuit. This order gets matched to the node wires
                by qargs first, then cargs, then conditions.

        Raises:
            DAGCircuitError: if met with unexpected predecessor/successors


for node in self._multi_graph.nodes:<EOL><INDENT>yield node<EOL><DEDENT>

Iterator for node values.

        Yield:
            node: the node.


all_bits = []<EOL>if cond is not None:<EOL><INDENT>all_bits.extend([(cond[<NUM_LIT:0>], j) for j in range(self.cregs[cond[<NUM_LIT:0>].name].size)])<EOL><DEDENT>return all_bits<EOL>

Return a list of bits in the given condition.

        Args:
            cond (tuple or None): optional condition (ClassicalRegister, int)

        Returns:
            list[(ClassicalRegister, idx)]: list of bits


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>three_q_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and len(node.qargs) >= <NUM_LIT:3>:<EOL><INDENT>three_q_nodes.append((node._node_id, node.data_dict))<EOL><DEDENT><DEDENT>return three_q_nodes<EOL>


if not nx.is_directed_acyclic_graph(self._multi_graph):<EOL><INDENT>raise DAGCircuitError("<STR_LIT>")<EOL><DEDENT>depth = nx.dag_longest_path_length(self._multi_graph) - <NUM_LIT:1><EOL>return depth if depth != -<NUM_LIT:1> else <NUM_LIT:0><EOL>

Return the circuit depth.
        Returns:
            int: the circuit depth
        Raises:
            DAGCircuitError: if not a directed acyclic graph


summary = {"<STR_LIT:size>": self.size(),<EOL>"<STR_LIT>": self.depth(),<EOL>"<STR_LIT:width>": self.width(),<EOL>"<STR_LIT>": self.num_cbits(),<EOL>"<STR_LIT>": self.num_tensor_factors(),<EOL>"<STR_LIT>": self.count_ops()}<EOL>return summary<EOL>

Return a dictionary of circuit properties.


def extend_back(self, dag, edge_map=None):

edge_map = edge_map or {}<EOL>for qreg in dag.qregs.values():<EOL><INDENT>if qreg.name not in self.qregs:<EOL><INDENT>self.add_qreg(QuantumRegister(qreg.size, qreg.name))<EOL><DEDENT>edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>if creg.name not in self.cregs:<EOL><INDENT>self.add_creg(ClassicalRegister(creg.size, creg.name))<EOL><DEDENT>edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])<EOL><DEDENT>self.compose_back(dag, edge_map)<EOL>

Add `dag` at the end of `self`, using `edge_map`.


return sum(creg.size for creg in self.cregs.values())<EOL>

Return the total number of bits used by the circuit.


return self._multi_graph.order() - <NUM_LIT:2> * len(self.wires)<EOL>


return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]<EOL>

Return a list of qubits as (QuantumRegister, index) pairs.


return (nd for nd in self.topological_nodes() if nd.type == '<STR_LIT>')<EOL>

Yield op nodes in topological order.

Returns:
    generator(DAGnode): op node in topological order


def _check_condition(self, name, condition):

<EOL>if condition is not None and condition[<NUM_LIT:0>].name not in self.cregs:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" % name)<EOL><DEDENT>

Verify that the condition is valid.

        Args:
            name (string): used for error reporting
            condition (tuple or None): a condition tuple (ClassicalRegister,int)

        Raises:
            DAGCircuitError: if conditioning on an invalid register


if self.data_dict['<STR_LIT:type>'] not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise QiskitError('<STR_LIT>' % str(self))<EOL><DEDENT>return self.data_dict.get('<STR_LIT>')<EOL>

Returns (Register, int) tuple where the int is the index of
the wire else None


return self.data_dict.get('<STR_LIT>', [])<EOL>

Returns list of (ClassicalRegister, int) tuples where the int is the index
of the cbit else an empty list


self.data_dict['<STR_LIT>'] = new_qargs<EOL>

Sets the qargs to be the given list of qargs


<EOL>if '<STR_LIT>' == node1.name == node2.name:<EOL><INDENT>return set(node1.qargs) == set(node2.qargs)<EOL><DEDENT>return node1.data_dict == node2.data_dict<EOL>

Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.

Args:
    node1 (DAGNode): A node to compare.
    node2 (DAGNode): The other node to compare.

Return:
    Bool: If node1 == node2


self.data_dict['<STR_LIT:name>'] = new_name<EOL>

Sets the name of the node to be the given value


super().__init__(*msg)<EOL>self.msg = '<STR_LIT:U+0020>'.join(msg)<EOL>


id0 = self._process_bit_id(node.children[<NUM_LIT:0>])<EOL>id1 = self._process_bit_id(node.children[<NUM_LIT:1>])<EOL>if not(len(id0) == len(id1) or len(id0) == <NUM_LIT:1> or len(id1) == <NUM_LIT:1>):<EOL><INDENT>raise QiskitError("<STR_LIT>",<EOL>"<STR_LIT>" % node.line, "<STR_LIT>" % node.file)<EOL><DEDENT>maxidx = max([len(id0), len(id1)])<EOL>for idx in range(maxidx):<EOL><INDENT>if len(id0) > <NUM_LIT:1> and len(id1) > <NUM_LIT:1>:<EOL><INDENT>self.dag.apply_operation_back(CXBase(), [id0[idx], id1[idx]], [], self.condition)<EOL><DEDENT>elif len(id0) > <NUM_LIT:1>:<EOL><INDENT>self.dag.apply_operation_back(CXBase(), [id0[idx], id1[<NUM_LIT:0>]], [], self.condition)<EOL><DEDENT>else:<EOL><INDENT>self.dag.apply_operation_back(CXBase(), [id0[<NUM_LIT:0>], id1[idx]], [], self.condition)<EOL><DEDENT><DEDENT>


def _create_dag_op(self, name, params, qargs):

if name == "<STR_LIT>":<EOL><INDENT>op_class = U0Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = U1Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = U2Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = U3Gate<EOL><DEDENT>elif name == "<STR_LIT:x>":<EOL><INDENT>op_class = XGate<EOL><DEDENT>elif name == "<STR_LIT:y>":<EOL><INDENT>op_class = YGate<EOL><DEDENT>elif name == "<STR_LIT:z>":<EOL><INDENT>op_class = ZGate<EOL><DEDENT>elif name == "<STR_LIT:t>":<EOL><INDENT>op_class = TGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = TdgGate<EOL><DEDENT>elif name == "<STR_LIT:s>":<EOL><INDENT>op_class = SGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = SdgGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = SwapGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RXGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RYGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RZGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = RZZGate<EOL><DEDENT>elif name == "<STR_LIT:id>":<EOL><INDENT>op_class = IdGate<EOL><DEDENT>elif name == "<STR_LIT:h>":<EOL><INDENT>op_class = HGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CnotGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CyGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CzGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CHGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = CrzGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = Cu1Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = Cu3Gate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = ToffoliGate<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>op_class = FredkinGate<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>" % name)<EOL><DEDENT>op = op_class(*params)<EOL>self.dag.apply_operation_back(op, qargs, [], condition=self.condition)<EOL>

Create a DAG node out of a parsed AST op node.

Args:
    name (str): operation name to apply to the dag.
    params (list): op parameters
    qargs (list(QuantumRegister, int)): qubits to attach to

Raises:
    QiskitError: if encountering a non-basis opaque gate


for kid in node.children:<EOL><INDENT>self._process_node(kid)<EOL><DEDENT>

Call process_node for all children of node.


density_matrix = np.outer(state.conjugate(), state)<EOL>if flatten:<EOL><INDENT>return density_matrix.flatten(order='<STR_LIT:F>')<EOL><DEDENT>return density_matrix<EOL>

maps a pure state to a state matrix

Args:
    state (ndarray): the number of qubits
    flatten (bool): determine if state matrix of column work
Returns:
    ndarray:  state_mat(2**num, 2**num) if flatten is false
    ndarray:  state_mat(4**num) if flatten is true stacked on by the column


U, s, Vh = la.svd(a, lapack_driver='<STR_LIT>')<EOL>S = np.diag(func(s))<EOL>return U.dot(S).dot(Vh)<EOL>

Apply real scalar function to singular values of a matrix.

    Args:
        a (array_like): (N, N) Matrix at which to evaluate the function.
        func (callable): Callable object that evaluates a scalar function f.

    Returns:
        ndarray: funm (N, N) Value of the matrix function specified by func
        evaluated at `A`.


def random_density_matrix(length, rank=None, method='<STR_LIT>', seed=None):

if method == '<STR_LIT>':<EOL><INDENT>return __random_density_hs(length, rank, seed)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return __random_density_bures(length, rank, seed)<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(method))<EOL><DEDENT>

Generate a random density matrix rho.

Args:
    length (int): the length of the density matrix.
    rank (int or None): the rank of the density matrix. The default
        value is full-rank.
    method (string): the method to use.
        'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric.
        'Bures': sample rho from the Bures metric.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: rho (length, length) a density matrix.
Raises:
    QiskitError: if the method is not valid.


def __random_density_hs(N, rank=None, seed=None):

G = __ginibre_matrix(N, rank, seed)<EOL>G = G.dot(G.conj().T)<EOL>return G / np.trace(G)<EOL>

Generate a random density matrix from the Hilbert-Schmidt metric.

Args:
    N (int): the length of the density matrix.
    rank (int or None): the rank of the density matrix. The default
        value is full-rank.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: rho (N,N  a density matrix.


def __ginibre_matrix(nrow, ncol=None, seed=None):

if ncol is None:<EOL><INDENT>ncol = nrow<EOL><DEDENT>if seed is not None:<EOL><INDENT>np.random.seed(seed)<EOL><DEDENT>G = np.random.normal(size=(nrow, ncol)) +np.random.normal(size=(nrow, ncol)) * <NUM_LIT><EOL>return G<EOL>

Return a normally distributed complex random matrix.

Args:
    nrow (int): number of rows in output matrix.
    ncol (int): number of columns in output matrix.
    seed (int): Optional. To set a random seed.
Returns:
    ndarray: A complex rectangular matrix where each real and imaginary
        entry is sampled from the normal distribution.


if not isinstance(observable, dict):<EOL><INDENT>observable = make_dict_observable(observable)<EOL><DEDENT>temp = <NUM_LIT:0><EOL>tot = sum(counts.values())<EOL>for key in counts:<EOL><INDENT>if key in observable:<EOL><INDENT>temp += counts[key] * observable[key] / tot<EOL><DEDENT><DEDENT>return temp<EOL>

Compute the mean value of an diagonal observable.

    Takes in a diagonal observable in dictionary, list or matrix format and then
    calculates the sum_i value(i) P(i) where value(i) is the value of the
    observable for state i.

    Args:
        counts (dict): a dict of outcomes from an experiment
        observable (dict or matrix or list): The observable to be averaged over.
        As an example, ZZ on qubits can be given as:
        * dict: {"00": 1, "11": 1, "01": -1, "10": -1}
        * matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]]
        * matrix diagonal (list): [1, -1, -1, 1]

    Returns:
        Double: Average of the observable


def process_fidelity(channel1, channel2, require_cptp=True):

<EOL>is_cptp1 = None<EOL>is_cptp2 = None<EOL>if isinstance(channel1, (list, np.ndarray)):<EOL><INDENT>channel1 = Operator(channel1)<EOL>if require_cptp:<EOL><INDENT>is_cptp1 = channel1.is_unitary()<EOL><DEDENT><DEDENT>if isinstance(channel2, (list, np.ndarray)):<EOL><INDENT>channel2 = Operator(channel2)<EOL>if require_cptp:<EOL><INDENT>is_cptp2 = channel2.is_unitary()<EOL><DEDENT><DEDENT>s1 = SuperOp(channel1)<EOL>s2 = SuperOp(channel2)<EOL>if require_cptp:<EOL><INDENT>if is_cptp1 is None:<EOL><INDENT>is_cptp1 = s1.is_cptp()<EOL><DEDENT>if not is_cptp1:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>if is_cptp2 is None:<EOL><INDENT>is_cptp2 = s2.is_cptp()<EOL><DEDENT>if not is_cptp2:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT><DEDENT>input_dim1, output_dim1 = s1.dim<EOL>input_dim2, output_dim2 = s2.dim<EOL>if input_dim1 != output_dim1 or input_dim2 != output_dim2:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>if input_dim1 != input_dim2:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>fidelity = np.trace(s1.compose(s2.adjoint()).data) / (input_dim1 ** <NUM_LIT:2>)<EOL>return fidelity<EOL>

Return the process fidelity between two quantum channels.

    This is given by

        F_p(E1, E2) = Tr[S2^dagger.S1])/dim^2

    where S1 and S2 are the SuperOp matrices for channels E1 and E2,
    and dim is the dimension of the input output statespace.

    Args:
        channel1 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        channel2 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        require_cptp (bool): require input channels to be CPTP [Default: True].

    Returns:
        array_like: The state fidelity F(state1, state2).

    Raises:
        QiskitError: if inputs channels do not have the same dimensions,
        have different input and output dimensions, or are not CPTP with
        `require_cptp=True`.


out = np.zeros(<NUM_LIT:4>, dtype=float)<EOL>if axis == '<STR_LIT:x>':<EOL><INDENT>out[<NUM_LIT:1>] = <NUM_LIT:1><EOL><DEDENT>elif axis == '<STR_LIT:y>':<EOL><INDENT>out[<NUM_LIT:2>] = <NUM_LIT:1><EOL><DEDENT>elif axis == '<STR_LIT:z>':<EOL><INDENT>out[<NUM_LIT:3>] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>out *= math.sin(angle/<NUM_LIT>)<EOL>out[<NUM_LIT:0>] = math.cos(angle/<NUM_LIT>)<EOL>return Quaternion(out)<EOL>

Return quaternion for rotation about given axis.

    Args:
        angle (float): Angle in radians.
        axis (str): Axis for rotation

    Returns:
        Quaternion: Quaternion for axis rotation.

    Raises:
        ValueError: Invalid input axis.


return la.norm(self.data)<EOL>


mat = self.to_matrix()<EOL>euler = np.zeros(<NUM_LIT:3>, dtype=float)<EOL>if mat[<NUM_LIT:2>, <NUM_LIT:2>] < <NUM_LIT:1>:<EOL><INDENT>if mat[<NUM_LIT:2>, <NUM_LIT:2>] > -<NUM_LIT:1>:<EOL><INDENT>euler[<NUM_LIT:0>] = math.atan2(mat[<NUM_LIT:1>, <NUM_LIT:2>], mat[<NUM_LIT:0>, <NUM_LIT:2>])<EOL>euler[<NUM_LIT:1>] = math.acos(mat[<NUM_LIT:2>, <NUM_LIT:2>])<EOL>euler[<NUM_LIT:2>] = math.atan2(mat[<NUM_LIT:2>, <NUM_LIT:1>], -mat[<NUM_LIT:2>, <NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>euler[<NUM_LIT:0>] = -math.atan2(mat[<NUM_LIT:1>, <NUM_LIT:0>], mat[<NUM_LIT:1>, <NUM_LIT:1>])<EOL>euler[<NUM_LIT:1>] = np.pi<EOL><DEDENT><DEDENT>else:<EOL><INDENT>euler[<NUM_LIT:0>] = math.atan2(mat[<NUM_LIT:1>, <NUM_LIT:0>], mat[<NUM_LIT:1>, <NUM_LIT:1>])<EOL><DEDENT>return euler<EOL>

Converts a unit-length quaternion to a sequence
        of ZYZ Euler angles.

        Returns:
            ndarray: Array of Euler angles.


def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):

if atol is None:<EOL><INDENT>atol = ATOL_DEFAULT<EOL><DEDENT>if rtol is None:<EOL><INDENT>rtol = RTOL_DEFAULT<EOL><DEDENT>if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):<EOL><INDENT>return False<EOL><DEDENT>vals = np.linalg.eigvalsh(mat)<EOL>for v in vals:<EOL><INDENT>if v < -atol:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Test if a matrix is positive semidefinite


def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):

if atol is None:<EOL><INDENT>atol = ATOL_DEFAULT<EOL><DEDENT>if rtol is None:<EOL><INDENT>rtol = RTOL_DEFAULT<EOL><DEDENT>mat = np.array(mat)<EOL>if mat.ndim != <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol)<EOL>


@abstractmethod<EOL><INDENT>def is_unitary(self, atol=None, rtol=None):<DEDENT>

pass<EOL>

Return True if operator is a unitary matrix.


return self._input_dim, self._output_dim<EOL>

Return tuple (input_shape, output_shape).


return self.__class__.RTOL<EOL>

The relative tolerence parameter for float comparisons.


pass<EOL>

Return the linear operator self + other.

        Args:
            other (complex): a complex number.

        Returns:
            Operator: the linear operator other * self.

        Raises:
            QiskitError: if other is not a valid complex number.


pass<EOL>

Convert operator to matrix operator class


mat = self.to_spmatrix()<EOL>return mat.toarray()<EOL>

r"""
        Convert Pauli to a matrix representation.

        Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$

        Returns:
            numpy.array: a matrix that represents the pauli.


z = [p for p in self._z]<EOL>x = [p for p in self._x]<EOL>ret = self.__class__.__name__ + "<STR_LIT>".format(z, x)<EOL>return ret<EOL>


def __init__(self, z=None, x=None, label=None):

if label is not None:<EOL><INDENT>a = Pauli.from_label(label)<EOL>self._z = a.z<EOL>self._x = a.x<EOL><DEDENT>else:<EOL><INDENT>self._init_from_bool(z, x)<EOL><DEDENT>

r"""Make the Pauli object.

        Note that, for the qubit index:
            - Order of z, x vectors is q_0 ... q_{n-1},
            - Order of pauli label is q_{n-1} ... q_0

        E.g.,
            - z and x vectors: z = [z_0 ... z_{n-1}], x = [x_0 ... x_{n-1}]
            - a pauli is $P_{n-1} \otimes ... \otimes P_0$

        Args:
            z (numpy.ndarray): boolean, z vector
            x (numpy.ndarray): boolean, x vector
            label (str): pauli label


return len(self._z)<EOL>


<EOL>from qiskit.quantum_info.operators.operator import Operator<EOL>return Operator(self.to_matrix())<EOL>


mat = sparse.coo_matrix(<NUM_LIT:1>)<EOL>for z, x in zip(self._z, self._x):<EOL><INDENT>if not z and not x:  <EOL><INDENT>mat = sparse.bmat([[mat, None], [None, mat]], format='<STR_LIT>')<EOL><DEDENT>elif z and not x:  <EOL><INDENT>mat = sparse.bmat([[mat, None], [None, -mat]], format='<STR_LIT>')<EOL><DEDENT>elif not z and x:  <EOL><INDENT>mat = sparse.bmat([[None, mat], [mat, None]], format='<STR_LIT>')<EOL><DEDENT>else:  <EOL><INDENT>mat = mat * <NUM_LIT><EOL>mat = sparse.bmat([[None, -mat], [mat, None]], format='<STR_LIT>')<EOL><DEDENT><DEDENT>return mat.tocsr()<EOL>

r"""
        Convert Pauli to a sparse matrix representation (CSR format).

        Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$

        Returns:
            scipy.sparse.csr_matrix: a sparse matrix with CSR format that
            represnets the pauli.


if z is None:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if x is None:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if len(z) != len(x):<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>".format(len(z), len(x)))<EOL><DEDENT>z = _make_np_bool(z)<EOL>x = _make_np_bool(x)<EOL>self._z = z<EOL>self._x = x<EOL>return self<EOL>

Construct pauli from boolean array.

        Args:
            z (numpy.ndarray): boolean, z vector
            x (numpy.ndarray): boolean, x vector

        Returns:
            Pauli: self

        Raises:
            QiskitError: if z or x are None or the length of z and x are different.


if len(self) != len(other):<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>".format(len(self), len(other)))<EOL><DEDENT>self._z = np.logical_xor(self._z, other.z)<EOL>self._x = np.logical_xor(self._x, other.x)<EOL>return self<EOL>

Multiply two Paulis.

        Returns:
            Pauli: the multiplied pauli and save to itself, in-place computation.

        Raises:
            QiskitError: if the number of qubits of two paulis are different.


return len(self)<EOL>


@classmethod<EOL><INDENT>def pauli_single(cls, num_qubits, index, pauli_label):<DEDENT>

tmp = Pauli.from_label(pauli_label)<EOL>z = np.zeros(num_qubits, dtype=np.bool)<EOL>x = np.zeros(num_qubits, dtype=np.bool)<EOL>z[index] = tmp.z[<NUM_LIT:0>]<EOL>x[index] = tmp.x[<NUM_LIT:0>]<EOL>return cls(z, x)<EOL>

Generate single qubit pauli at index with pauli_label with length num_qubits.

Args:
    num_qubits (int): the length of pauli
    index (int): the qubit index to insert the single qubii
    pauli_label (str): pauli

Returns:
    Pauli: single qubit pauli


if not isinstance(other, Operator):<EOL><INDENT>other = Operator(other)<EOL><DEDENT>if self.dim != other.dim:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>return Operator(self.data - other.data, self.input_dims(),<EOL>self.output_dims())<EOL>

Return the operator self - other.

        Args:
            other (Operator): an operator object.

        Returns:
            Operator: the operator self - other.

        Raises:
            QiskitError: if other is not an operator, or has incompatible
            dimensions.


def compose(self, other, qargs=None, front=False):

<EOL>if not isinstance(other, Operator):<EOL><INDENT>other = Operator(other)<EOL><DEDENT>if front and self.input_dims(qargs=qargs) != other.output_dims():<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>if not front and self.output_dims(qargs=qargs) != other.input_dims():<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>if qargs is None:<EOL><INDENT>if front:<EOL><INDENT>input_dims = other.input_dims()<EOL>output_dims = self.output_dims()<EOL>data = np.dot(self._data, other.data)<EOL><DEDENT>else:<EOL><INDENT>input_dims = self.input_dims()<EOL>output_dims = other.output_dims()<EOL>data = np.dot(other.data, self._data)<EOL><DEDENT>return Operator(data, input_dims, output_dims)<EOL><DEDENT>return self._compose_subsystem(other, qargs, front)<EOL>

Return the composition channel self∘other.

        Args:
            other (Operator): an operator object.
            qargs (list): a list of subsystem positions to compose other on.
            front (bool): If False compose in standard order other(self(input))
                          otherwise compose in reverse order self(other(input))
                          [default: False]

        Returns:
            Operator: The composed operator.

        Raises:
            QiskitError: if other cannot be converted to an Operator or has
            incompatible dimensions.


return self._tensor_product(other, reverse=True)<EOL>

Return the tensor product operator other ⊗ self.

        Args:
            other (Operator): an operator object.

        Returns:
            Operator: the tensor product operator other ⊗ self.

        Raises:
            QiskitError: if other cannot be converted to an operator.


def _tensor_product(self, other, reverse=False):

<EOL>if not isinstance(other, Operator):<EOL><INDENT>other = Operator(other)<EOL><DEDENT>if reverse:<EOL><INDENT>input_dims = self.input_dims() + other.input_dims()<EOL>output_dims = self.output_dims() + other.output_dims()<EOL>data = np.kron(other._data, self._data)<EOL><DEDENT>else:<EOL><INDENT>input_dims = other.input_dims() + self.input_dims()<EOL>output_dims = other.output_dims() + self.output_dims()<EOL>data = np.kron(self._data, other._data)<EOL><DEDENT>return Operator(data, input_dims, output_dims)<EOL>

Return the tensor product operator.

        Args:
            other (Operator): another operator.
            reverse (bool): If False return self ⊗ other, if True return
                            if True return (other ⊗ self) [Default: False
        Returns:
            Operator: the tensor product operator.

        Raises:
            QiskitError: if other cannot be converted into an Operator.


from qiskit.extensions.unitary import UnitaryGate<EOL>return UnitaryGate(self.data)<EOL>


def _compose_subsystem(self, other, qargs, front=False):

<EOL>input_dims = list(self.input_dims())<EOL>output_dims = list(self.output_dims())<EOL>if front:<EOL><INDENT>num_indices = len(self.input_dims())<EOL>shift = len(self.output_dims())<EOL>right_mul = True<EOL>for pos, qubit in enumerate(qargs):<EOL><INDENT>input_dims[qubit] = other._input_dims[pos]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>num_indices = len(self.output_dims())<EOL>shift = <NUM_LIT:0><EOL>right_mul = False<EOL>for pos, qubit in enumerate(qargs):<EOL><INDENT>output_dims[qubit] = other._output_dims[pos]<EOL><DEDENT><DEDENT>tensor = np.reshape(self.data, self._shape)<EOL>mat = np.reshape(other.data, other._shape)<EOL>indices = [num_indices - <NUM_LIT:1> - qubit for qubit in qargs]<EOL>final_shape = [np.product(output_dims), np.product(input_dims)]<EOL>data = np.reshape(<EOL>self._einsum_matmul(tensor, mat, indices, shift, right_mul),<EOL>final_shape)<EOL>return Operator(data, input_dims, output_dims)<EOL>


def _append_instruction(self, obj, qargs=None):

if isinstance(obj, Instruction):<EOL><INDENT>mat = None<EOL>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>mat = obj.to_matrix()<EOL><DEDENT>except QiskitError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if mat is not None:<EOL><INDENT>op = self.compose(mat, qargs=qargs)<EOL>self._data = op.data<EOL><DEDENT>else:<EOL><INDENT>if obj.definition is None:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(obj.name))<EOL><DEDENT>for instr, qregs, cregs in obj.definition:<EOL><INDENT>if cregs:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>'.format(<EOL>instr.name))<EOL><DEDENT>new_qargs = [tup[<NUM_LIT:1>] for tup in qregs]<EOL>self._append_instruction(instr, qargs=new_qargs)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>

Update the current Operator by apply an instruction.


if not isinstance(other, Number):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>return Operator(other * self.data, self.input_dims(),<EOL>self.output_dims())<EOL>

Return the operator self + other.

        Args:
            other (complex): a complex number.

        Returns:
            Operator: the operator other * self.

        Raises:
            QiskitError: if other is not a valid complex number.


def _evolve_subsystem(self, state, qargs):

mat = np.reshape(self.data, self._shape)<EOL>state_size = len(state)<EOL>state_dims = self._automatic_dims(None, state_size)<EOL>if self.input_dims() != len(qargs) * (<NUM_LIT:2>,):<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if state.ndim == <NUM_LIT:1>:<EOL><INDENT>tensor = np.reshape(state, state_dims)<EOL>indices = [len(state_dims) - <NUM_LIT:1> - qubit for qubit in qargs]<EOL>tensor = self._einsum_matmul(tensor, mat, indices)<EOL>return np.reshape(tensor, state_size)<EOL><DEDENT>tensor = np.reshape(state, <NUM_LIT:2> * state_dims)<EOL>indices = [len(state_dims) - <NUM_LIT:1> - qubit for qubit in qargs]<EOL>right_shift = len(state_dims)<EOL>tensor = self._einsum_matmul(tensor, mat, indices)<EOL>tensor = self._einsum_matmul(<EOL>tensor, np.conj(mat), indices, shift=right_shift)<EOL>return np.reshape(tensor, [state_size, state_size])<EOL>

Evolve a quantum state by the operator.

        Args:
            state (QuantumState): The input statevector or density matrix.
            qargs (list): a list of QuantumState subsystem positions to apply
                           the operator on.

        Returns:
            QuantumState: the output quantum state.

        Raises:
            QiskitError: if the operator dimension does not match the
            specified QuantumState subsystem dimensions.


if qargs is not None:<EOL><INDENT>return Chi(<EOL>SuperOp(self).compose(other, qargs=qargs, front=front))<EOL><DEDENT>if not isinstance(other, Choi):<EOL><INDENT>other = Choi(other)<EOL><DEDENT>if front and self._input_dim != other._output_dim:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>if not front and self._output_dim != other._input_dim:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>return Chi(Choi(self).compose(other, front=front))<EOL>

Return the composition channel self∘other.

        Args:
            other (QuantumChannel): a quantum channel.
            qargs (list): a list of subsystem positions to compose other on.
            front (bool): If False compose in standard order other(self(input))
                          otherwise compose in reverse order self(other(input))
                          [default: False]

        Returns:
            Chi: The composition channel as a Chi object.

        Raises:
            QiskitError: if other is not a QuantumChannel subclass, or
            has incompatible dimensions.


return self._tensor_product(other, reverse=False)<EOL>

Return the tensor product channel self ⊗ other.

        Args:
            other (QuantumChannel): a quantum channel.

        Returns:
            SuperOp: the tensor product channel self ⊗ other as a SuperOp
            object.

        Raises:
            QiskitError: if other cannot be converted to a channel.


state = self._format_state(state, density_matrix=True)<EOL>if qargs is None:<EOL><INDENT>if state.shape[<NUM_LIT:0>] != self._input_dim:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>shape_in = self._input_dim * self._input_dim<EOL>shape_out = (self._output_dim, self._output_dim)<EOL>return np.reshape(<EOL>np.dot(self._data, np.reshape(state, shape_in, order='<STR_LIT:F>')),<EOL>shape_out,<EOL>order='<STR_LIT:F>')<EOL><DEDENT>return self._evolve_subsystem(state, qargs)<EOL>

Evolve a quantum state by the QuantumChannel.

        Args:
            state (QuantumState): The input statevector or density matrix.
            qargs (list): a list of QuantumState subsystem positions to apply
                           the operator on.

        Returns:
            DensityMatrix: the output quantum state as a density matrix.

        Raises:
            QiskitError: if the operator dimension does not match the
            specified QuantumState subsystem dimensions.


Return the tensor product channel other ⊗ self.

        Args:
            other (QuantumChannel): a quantum channel subclass.

        Returns:
            Stinespring: the tensor product channel other ⊗ self as a
            Stinespring object.

        Raises:
            QiskitError: if other cannot be converted to a channel.


<EOL>if qargs is not None:<EOL><INDENT>return SuperOp(self)._evolve(state, qargs)<EOL><DEDENT>state = self._format_state(state)<EOL>if state.shape[<NUM_LIT:0>] != self._input_dim:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if state.ndim == <NUM_LIT:1> and self._data[<NUM_LIT:1>] is None andself._data[<NUM_LIT:0>].shape[<NUM_LIT:0>] // self._output_dim == <NUM_LIT:1>:<EOL><INDENT>return np.dot(self._data[<NUM_LIT:0>], state)<EOL><DEDENT>state = self._format_state(state, density_matrix=True)<EOL>stine_l, stine_r = self._data<EOL>if stine_r is None:<EOL><INDENT>stine_r = stine_l<EOL><DEDENT>din, dout = self.dim<EOL>dtr = stine_l.shape[<NUM_LIT:0>] // dout<EOL>shape = (dout, dtr, din)<EOL>return np.einsum('<STR_LIT>', np.reshape(stine_l, shape), state,<EOL>np.reshape(np.conjugate(stine_r), shape))<EOL>

Evolve a quantum state by the QuantumChannel.

        Args:
            state (QuantumState): The input statevector or density matrix.
            qargs (list): a list of QuantumState subsystem positions to apply
                           the operator on.

        Returns:
            QuantumState: the output quantum state.

        Raises:
            QiskitError: if the operator dimension does not match the
            specified QuantumState subsystem dimensions.


Return the tensor product channel self ⊗ other.

        Args:
            other (QuantumChannel): a quantum channel subclass.

        Returns:
            Stinespring: the tensor product channel other ⊗ self as a
            Stinespring object.

        Raises:
            QiskitError: if other cannot be converted to a channel.


if not isinstance(other, Number):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if isinstance(other, complex) or other < <NUM_LIT:1>:<EOL><INDENT>return Stinespring(Choi(self).multiply(other))<EOL><DEDENT>num = np.sqrt(other)<EOL>stine_l, stine_r = self._data<EOL>stine_l = num * self._data[<NUM_LIT:0>]<EOL>stine_r = None<EOL>if self._data[<NUM_LIT:1>] is not None:<EOL><INDENT>stine_r = num * self._data[<NUM_LIT:1>]<EOL><DEDENT>return Stinespring((stine_l, stine_r), self.input_dims(),<EOL>self.output_dims())<EOL>

Return the QuantumChannel self + other.

        Args:
            other (complex): a complex number.

        Returns:
            Stinespring: the scalar multiplication other * self as a
            Stinespring object.

        Raises:
            QiskitError: if other is not a valid scalar.


def _ptm_to_superop(data, input_dim, output_dim):

num_qubits = int(np.log2(input_dim))<EOL>return _transform_from_pauli(data, num_qubits)<EOL>

Transform PTM representation to SuperOp representation.


def _stinespring_to_superop(data, input_dim, output_dim):

trace_dim = data[<NUM_LIT:0>].shape[<NUM_LIT:0>] // output_dim<EOL>stine_l = np.reshape(data[<NUM_LIT:0>], (output_dim, trace_dim, input_dim))<EOL>if data[<NUM_LIT:1>] is None:<EOL><INDENT>stine_r = stine_l<EOL><DEDENT>else:<EOL><INDENT>stine_r = np.reshape(data[<NUM_LIT:1>], (output_dim, trace_dim, input_dim))<EOL><DEDENT>return np.reshape(<EOL>np.einsum('<STR_LIT>', stine_r.conj(), stine_l),<EOL>(output_dim * output_dim, input_dim * input_dim))<EOL>

Transform Stinespring representation to SuperOp representation.


def _choi_to_chi(data, input_dim, output_dim):

num_qubits = int(np.log2(input_dim))<EOL>return _transform_to_pauli(data, num_qubits)<EOL>

Transform Choi representation to the Chi representation.


def _kraus_to_stinespring(data, input_dim, output_dim):

stine_pair = [None, None]<EOL>for i, kraus in enumerate(data):<EOL><INDENT>if kraus is not None:<EOL><INDENT>num_kraus = len(kraus)<EOL>stine = np.zeros((output_dim * num_kraus, input_dim),<EOL>dtype=complex)<EOL>for j, mat in enumerate(kraus):<EOL><INDENT>vec = np.zeros(num_kraus)<EOL>vec[j] = <NUM_LIT:1><EOL>stine += np.kron(mat, vec[:, None])<EOL><DEDENT>stine_pair[i] = stine<EOL><DEDENT><DEDENT>return tuple(stine_pair)<EOL>

Transform Kraus representation to Stinespring representation.


def _kraus_to_operator(data, input_dim, output_dim):

if data[<NUM_LIT:1>] is not None or len(data[<NUM_LIT:0>]) > <NUM_LIT:1>:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>return data[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>

Transform Kraus representation to Operator representation.


def _choi_to_superop(data, input_dim, output_dim):

shape = (input_dim, output_dim, input_dim, output_dim)<EOL>return _reshuffle(data, shape)<EOL>

Transform Choi to SuperOp representation.


<EOL>basis_mat = np.array(<EOL>[[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>], [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>], [<NUM_LIT:0>, -<NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>], [<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:0>, -<NUM_LIT:1>]],<EOL>dtype=complex)<EOL>cob = basis_mat<EOL>for _ in range(num_qubits - <NUM_LIT:1>):<EOL><INDENT>dim = int(np.sqrt(len(cob)))<EOL>cob = np.reshape(<EOL>np.transpose(<EOL>np.reshape(<EOL>np.kron(basis_mat, cob), (<NUM_LIT:4>, dim * dim, <NUM_LIT:2>, <NUM_LIT:2>, dim, dim)),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:5>)), (<NUM_LIT:4> * dim * dim, <NUM_LIT:4> * dim * dim))<EOL><DEDENT>return np.dot(np.dot(cob, data), cob.conj().T) / <NUM_LIT:2>**num_qubits<EOL>

Change of basis of bipartite matrix represenation.


def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):

<EOL>if is_hermitian_matrix(data, atol=atol):<EOL><INDENT>w, v = la.eigh(data)<EOL>if len(w[w < -atol]) == <NUM_LIT:0>:<EOL><INDENT>kraus = []<EOL>for val, vec in zip(w, v.T):<EOL><INDENT>if abs(val) > atol:<EOL><INDENT>k = np.sqrt(val) * vec.reshape(<EOL>(output_dim, input_dim), order='<STR_LIT:F>')<EOL>kraus.append(k)<EOL><DEDENT><DEDENT>if not kraus:<EOL><INDENT>kraus.append(np.zeros((output_dim, input_dim), dtype=complex))<EOL><DEDENT>return (kraus, None)<EOL><DEDENT><DEDENT>mat_u, svals, mat_vh = la.svd(data)<EOL>kraus_l = []<EOL>kraus_r = []<EOL>for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()):<EOL><INDENT>kraus_l.append(<EOL>np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='<STR_LIT:F>'))<EOL>kraus_r.append(<EOL>np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='<STR_LIT:F>'))<EOL><DEDENT>return (kraus_l, kraus_r)<EOL>

Transform Choi representation to Kraus representation.


def _stinespring_to_operator(data, input_dim, output_dim):

trace_dim = data[<NUM_LIT:0>].shape[<NUM_LIT:0>] // output_dim<EOL>if data[<NUM_LIT:1>] is not None or trace_dim != <NUM_LIT:1>:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>return data[<NUM_LIT:0>]<EOL>

Transform Stinespring representation to Operator representation.


def _is_cp_helper(self, choi, atol, rtol):

if atol is None:<EOL><INDENT>atol = self._atol<EOL><DEDENT>if rtol is None:<EOL><INDENT>rtol = self._rtol<EOL><DEDENT>return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol)<EOL>

Test if a channel is completely-positive (CP)


def is_unitary(self, atol=None, rtol=None):

try:<EOL><INDENT>op = self.to_operator()<EOL>return op.is_unitary(atol=atol, rtol=rtol)<EOL><DEDENT>except QiskitError:<EOL><INDENT>return False<EOL><DEDENT>

Return True if QuantumChannel is a unitary channel.


from qiskit.circuit.instruction import Instruction<EOL>n_qubits = int(np.log2(self._input_dim))<EOL>if self._input_dim != self._output_dim or <NUM_LIT:2>**n_qubits != self._input_dim:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if not self.is_cptp():<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>kraus, _ = _to_kraus(self.rep, self._data, *self.dim)<EOL>if len(kraus) == <NUM_LIT:1>:<EOL><INDENT>return Operator(kraus[<NUM_LIT:0>]).to_instruction()<EOL><DEDENT>return Instruction('<STR_LIT>', n_qubits, <NUM_LIT:0>, kraus)<EOL>

Convert to a Kraus or UnitaryGate circuit instruction.

        If the channel is unitary it will be added as a unitary gate,
        otherwise it will be added as a kraus simulator instruction.

        Returns:
            Instruction: A kraus instruction for the channel.

        Raises:
            QiskitError: if input data is not an N-qubit CPTP quantum channel.


choi = _to_choi(self.rep, self._data, *self.dim)<EOL>return self._is_tp_helper(choi, atol, rtol)<EOL>


return (self._input_dim, self._output_dim, self._input_dim,<EOL>self._output_dim)<EOL>


if not isinstance(other, Number):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>return Choi(other * self._data, self._input_dims, self._output_dims)<EOL>

Return the QuantumChannel self + other.

        Args:
            other (complex): a complex number.

        Returns:
            Choi: the scalar multiplication other * self as a Choi object.

        Raises:
            QiskitError: if other is not a valid scalar.


kraus_l, kraus_r = self._data<EOL>kraus_l = [k.T for k in kraus_l]<EOL>if kraus_r is not None:<EOL><INDENT>kraus_r = [k.T for k in kraus_r]<EOL><DEDENT>return Kraus((kraus_l, kraus_r),<EOL>input_dims=self.output_dims(),<EOL>output_dims=self.input_dims())<EOL>

Return the transpose of the QuantumChannel.


if n > <NUM_LIT:0>:<EOL><INDENT>return super().power(n)<EOL><DEDENT>return Kraus(SuperOp(self).power(n))<EOL>

The matrix power of the channel.

        Args:
            n (int): compute the matrix power of the superoperator matrix.

        Returns:
            Kraus: the matrix power of the SuperOp converted to a Kraus channel.

        Raises:
            QiskitError: if the input and output dimensions of the
            QuantumChannel are not equal, or the power is not an integer.


def __init__(self, data, input_dims=None, output_dims=None):

<EOL>if isinstance(data, (list, tuple, np.ndarray)):<EOL><INDENT>if isinstance(data, np.ndarray) or np.array(data).ndim == <NUM_LIT:2>:<EOL><INDENT>kraus = ([np.array(data, dtype=complex)], None)<EOL>shape = kraus[<NUM_LIT:0>][<NUM_LIT:0>].shape<EOL><DEDENT>elif isinstance(data, list) and len(data) > <NUM_LIT:0>:<EOL><INDENT>kraus = [np.array(data[<NUM_LIT:0>], dtype=complex)]<EOL>shape = kraus[<NUM_LIT:0>].shape<EOL>for i in data[<NUM_LIT:1>:]:<EOL><INDENT>op = np.array(i, dtype=complex)<EOL>if op.shape != shape:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>")<EOL><DEDENT>kraus.append(op)<EOL><DEDENT>kraus = (kraus, None)<EOL><DEDENT>elif isinstance(data,<EOL>tuple) and len(data) == <NUM_LIT:2> and len(data[<NUM_LIT:0>]) > <NUM_LIT:0>:<EOL><INDENT>kraus_left = [np.array(data[<NUM_LIT:0>][<NUM_LIT:0>], dtype=complex)]<EOL>shape = kraus_left[<NUM_LIT:0>].shape<EOL>for i in data[<NUM_LIT:0>][<NUM_LIT:1>:]:<EOL><INDENT>op = np.array(i, dtype=complex)<EOL>if op.shape != shape:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>")<EOL><DEDENT>kraus_left.append(op)<EOL><DEDENT>if data[<NUM_LIT:1>] is None:<EOL><INDENT>kraus = (kraus_left, None)<EOL><DEDENT>else:<EOL><INDENT>kraus_right = []<EOL>for i in data[<NUM_LIT:1>]:<EOL><INDENT>op = np.array(i, dtype=complex)<EOL>if op.shape != shape:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>")<EOL><DEDENT>kraus_right.append(op)<EOL><DEDENT>kraus = (kraus_left, kraus_right)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(data, (QuantumCircuit, Instruction)):<EOL><INDENT>data = SuperOp._instruction_to_superop(data)<EOL><DEDENT>else:<EOL><INDENT>data = self._init_transformer(data)<EOL><DEDENT>input_dim, output_dim = data.dim<EOL>kraus = _to_kraus(data.rep, data._data, input_dim, output_dim)<EOL>if input_dims is None:<EOL><INDENT>input_dims = data.input_dims()<EOL><DEDENT>if output_dims is None:<EOL><INDENT>output_dims = data.output_dims()<EOL><DEDENT><DEDENT>output_dim, input_dim = kraus[<NUM_LIT:0>][<NUM_LIT:0>].shape<EOL>input_dims = self._automatic_dims(input_dims, input_dim)<EOL>output_dims = self._automatic_dims(output_dims, output_dim)<EOL>if kraus[<NUM_LIT:1>] is None or np.allclose(kraus[<NUM_LIT:0>], kraus[<NUM_LIT:1>]):<EOL><INDENT>super().__init__('<STR_LIT>', (kraus[<NUM_LIT:0>], None), input_dims,<EOL>output_dims)<EOL><DEDENT>else:<EOL><INDENT>super().__init__('<STR_LIT>', kraus, input_dims, output_dims)<EOL><DEDENT>

Initialize a quantum channel Kraus operator.

        Args:
            data (QuantumCircuit or
                  Instruction or
                  BaseOperator or
                  matrix): data to initialize superoperator.
            input_dims (tuple): the input subsystem dimensions.
                                [Default: None]
            output_dims (tuple): the output subsystem dimensions.
                                 [Default: None]

        Raises:
            QiskitError: if input data cannot be initialized as a
            a list of Kraus matrices.

        Additional Information
        ----------------------
        If the input or output dimensions are None, they will be
        automatically determined from the input data. If the input data is
        a list of Numpy arrays of shape (2**N, 2**N) qubit systems will be used. If
        the input does not correspond to an N-qubit channel, it will assign a
        single subsystem with dimension specifed by the shape of the input.


if not isinstance(other, PTM):<EOL><INDENT>other = PTM(other)<EOL><DEDENT>if reverse:<EOL><INDENT>input_dims = self.input_dims() + other.input_dims()<EOL>output_dims = self.output_dims() + other.output_dims()<EOL>data = np.kron(other.data, self._data)<EOL><DEDENT>else:<EOL><INDENT>input_dims = other.input_dims() + self.input_dims()<EOL>output_dims = other.output_dims() + self.output_dims()<EOL>data = np.kron(self._data, other.data)<EOL><DEDENT>return PTM(data, input_dims, output_dims)<EOL>

Return the tensor product channel.

        Args:
            other (QuantumChannel): a quantum channel.
            reverse (bool): If False return self ⊗ other, if True return
                            if True return (other ⊗ self) [Default: False
        Returns:
            PTM: the tensor product channel as a PTM object.

        Raises:
            QiskitError: if other cannot be converted to a channel.


<EOL>return PTM(SuperOp(self).conjugate())<EOL>

Return the conjugate of the QuantumChannel.


return self._tensor_product(other, reverse=True)<EOL>

Return the tensor product channel other ⊗ self.

        Args:
            other (QuantumChannel): a quantum channel.

        Returns:
            PTM: the tensor product channel other ⊗ self as a PTM object.

        Raises:
            QiskitError: if other cannot be converted to a channel.


if not isinstance(other, Number):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>return PTM(other * self._data, self._input_dims, self._output_dims)<EOL>

Return the QuantumChannel self + other.

        Args:
            other (complex): a complex number.

        Returns:
            PTM: the scalar multiplication other * self as a PTM object.

        Raises:
            QiskitError: if other is not a valid scalar.


return SuperOp(self)._evolve(state, qargs)<EOL>

Evolve a quantum state by the QuantumChannel.

        Args:
            state (QuantumState): The input statevector or density matrix.
            qargs (list): a list of QuantumState subsystem positions to apply
                           the operator on.

        Returns:
            DensityMatrix: the output quantum state as a density matrix.


run_config = qobj.config.to_dict()<EOL>user_qobj_header = qobj.header.to_dict()<EOL>circuits = _experiments_to_circuits(qobj)<EOL>return circuits, run_config, user_qobj_header<EOL>

Dissasemble a qobj and return the circuits, run_config, and user header

    Args:
        qobj (Qobj): The input qobj object to dissasemble
    Returns:
        circuits (list): A list of quantum circuits
        run_config (dict): The dist of the run config
        user_qobj_header (dict): The dict of any user headers in the qobj


def assemble_circuits(circuits, qobj_id=None, qobj_header=None, run_config=None):

qobj_config = QasmQobjConfig()<EOL>if run_config:<EOL><INDENT>qobj_config = QasmQobjConfig(**run_config.to_dict())<EOL><DEDENT>experiments = []<EOL>max_n_qubits = <NUM_LIT:0><EOL>max_memory_slots = <NUM_LIT:0><EOL>for circuit in circuits:<EOL><INDENT>n_qubits = <NUM_LIT:0><EOL>memory_slots = <NUM_LIT:0><EOL>qubit_labels = []<EOL>clbit_labels = []<EOL>qreg_sizes = []<EOL>creg_sizes = []<EOL>for qreg in circuit.qregs:<EOL><INDENT>qreg_sizes.append([qreg.name, qreg.size])<EOL>for j in range(qreg.size):<EOL><INDENT>qubit_labels.append([qreg.name, j])<EOL><DEDENT>n_qubits += qreg.size<EOL><DEDENT>for creg in circuit.cregs:<EOL><INDENT>creg_sizes.append([creg.name, creg.size])<EOL>for j in range(creg.size):<EOL><INDENT>clbit_labels.append([creg.name, j])<EOL><DEDENT>memory_slots += creg.size<EOL><DEDENT>experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels,<EOL>n_qubits=n_qubits,<EOL>qreg_sizes=qreg_sizes,<EOL>clbit_labels=clbit_labels,<EOL>memory_slots=memory_slots,<EOL>creg_sizes=creg_sizes,<EOL>name=circuit.name)<EOL>experimentconfig = QasmQobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots)<EOL>is_conditional_experiment = any(op.control for (op, qargs, cargs) in circuit.data)<EOL>max_conditional_idx = <NUM_LIT:0><EOL>instructions = []<EOL>for op_context in circuit.data:<EOL><INDENT>instruction = op_context[<NUM_LIT:0>].assemble()<EOL>qargs = op_context[<NUM_LIT:1>]<EOL>cargs = op_context[<NUM_LIT:2>]<EOL>if qargs:<EOL><INDENT>qubit_indices = [qubit_labels.index([qubit[<NUM_LIT:0>].name, qubit[<NUM_LIT:1>]])<EOL>for qubit in qargs]<EOL>instruction.qubits = qubit_indices<EOL><DEDENT>if cargs:<EOL><INDENT>clbit_indices = [clbit_labels.index([clbit[<NUM_LIT:0>].name, clbit[<NUM_LIT:1>]])<EOL>for clbit in cargs]<EOL>instruction.memory = clbit_indices<EOL>if instruction.name == "<STR_LIT>" and is_conditional_experiment:<EOL><INDENT>instruction.register = clbit_indices<EOL><DEDENT><DEDENT>if hasattr(instruction, '<STR_LIT>'):<EOL><INDENT>ctrl_reg, ctrl_val = instruction._control<EOL>mask = <NUM_LIT:0><EOL>val = <NUM_LIT:0><EOL>for clbit in clbit_labels:<EOL><INDENT>if clbit[<NUM_LIT:0>] == ctrl_reg.name:<EOL><INDENT>mask |= (<NUM_LIT:1> << clbit_labels.index(clbit))<EOL>val |= (((ctrl_val >> clbit[<NUM_LIT:1>]) & <NUM_LIT:1>) << clbit_labels.index(clbit))<EOL><DEDENT><DEDENT>conditional_reg_idx = memory_slots + max_conditional_idx<EOL>conversion_bfunc = QasmQobjInstruction(name='<STR_LIT>',<EOL>mask="<STR_LIT>" % mask,<EOL>relation='<STR_LIT>',<EOL>val="<STR_LIT>" % val,<EOL>register=conditional_reg_idx)<EOL>instructions.append(conversion_bfunc)<EOL>instruction.conditional = conditional_reg_idx<EOL>max_conditional_idx += <NUM_LIT:1><EOL>del instruction._control<EOL><DEDENT>instructions.append(instruction)<EOL><DEDENT>experiments.append(QasmQobjExperiment(instructions=instructions, header=experimentheader,<EOL>config=experimentconfig))<EOL>if n_qubits > max_n_qubits:<EOL><INDENT>max_n_qubits = n_qubits<EOL><DEDENT>if memory_slots > max_memory_slots:<EOL><INDENT>max_memory_slots = memory_slots<EOL><DEDENT><DEDENT>qobj_config.memory_slots = max_memory_slots<EOL>qobj_config.n_qubits = max_n_qubits<EOL>return QasmQobj(qobj_id=qobj_id,<EOL>config=qobj_config,<EOL>experiments=experiments,<EOL>header=qobj_header)<EOL>

Assembles a list of circuits into a qobj which can be run on the backend.

    Args:
        circuits (list[QuantumCircuits]): circuit(s) to assemble
        qobj_id (int): identifier for the generated qobj
        qobj_header (QobjHeader): header to pass to the results
        run_config (RunConfig): configuration of the runtime environment

    Returns:
        QasmQobj: the Qobj to be run on the backends


def _parse_transpile_args(circuits, backend,<EOL>basis_gates, coupling_map, backend_properties,<EOL>initial_layout, seed_transpiler, optimization_level,<EOL>pass_manager):

<EOL>num_circuits = len(circuits)<EOL>basis_gates = _parse_basis_gates(basis_gates, backend, circuits)<EOL>coupling_map = _parse_coupling_map(coupling_map, backend, num_circuits)<EOL>backend_properties = _parse_backend_properties(backend_properties, backend, num_circuits)<EOL>initial_layout = _parse_initial_layout(initial_layout, circuits)<EOL>seed_transpiler = _parse_seed_transpiler(seed_transpiler, num_circuits)<EOL>optimization_level = _parse_optimization_level(optimization_level, num_circuits)<EOL>pass_manager = _parse_pass_manager(pass_manager, num_circuits)<EOL>transpile_configs = []<EOL>for args in zip(basis_gates, coupling_map, backend_properties, initial_layout,<EOL>seed_transpiler, optimization_level, pass_manager):<EOL><INDENT>transpile_config = TranspileConfig(basis_gates=args[<NUM_LIT:0>],<EOL>coupling_map=args[<NUM_LIT:1>],<EOL>backend_properties=args[<NUM_LIT:2>],<EOL>initial_layout=args[<NUM_LIT:3>],<EOL>seed_transpiler=args[<NUM_LIT:4>],<EOL>optimization_level=args[<NUM_LIT:5>],<EOL>pass_manager=args[<NUM_LIT:6>])<EOL>transpile_configs.append(transpile_config)<EOL><DEDENT>return transpile_configs<EOL>

Resolve the various types of args allowed to the transpile() function through
    duck typing, overriding args, etc. Refer to the transpile() docstring for details on
    what types of inputs are allowed.

    Here the args are resolved by converting them to standard instances, and prioritizing
    them in case a transpile option is passed through multiple args (explicitly setting an
    arg has more priority than the arg set by backend)

    Returns:
        list[TranspileConfig]: a transpile config for each circuit, which is a standardized
            object that configures the transpiler and determines the pass manager to use.


def _multiplex(self, target_gate, list_of_angles):

list_len = len(list_of_angles)<EOL>local_num_qubits = int(math.log2(list_len)) + <NUM_LIT:1><EOL>q = QuantumRegister(local_num_qubits)<EOL>circuit = QuantumCircuit(q, name="<STR_LIT>" + local_num_qubits.__str__())<EOL>lsb = q[<NUM_LIT:0>]<EOL>msb = q[local_num_qubits - <NUM_LIT:1>]<EOL>if local_num_qubits == <NUM_LIT:1>:<EOL><INDENT>circuit.append(target_gate(list_of_angles[<NUM_LIT:0>]), [q[<NUM_LIT:0>]])<EOL>return circuit<EOL><DEDENT>angle_weight = scipy.kron([[<NUM_LIT:0.5>, <NUM_LIT:0.5>], [<NUM_LIT:0.5>, -<NUM_LIT:0.5>]],<EOL>np.identity(<NUM_LIT:2> ** (local_num_qubits - <NUM_LIT:2>)))<EOL>list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist()<EOL>multiplex_1 = self._multiplex(target_gate, list_of_angles[<NUM_LIT:0>:(list_len // <NUM_LIT:2>)])<EOL>circuit.append(multiplex_1.to_instruction(), q[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL>circuit.append(CnotGate(), [msb, lsb])<EOL>multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // <NUM_LIT:2>):])<EOL>if list_len > <NUM_LIT:1>:<EOL><INDENT>circuit.append(multiplex_2.to_instruction().mirror(), q[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>circuit.append(multiplex_2.to_instruction(), q[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL><DEDENT>circuit.append(CnotGate(), [msb, lsb])<EOL>return circuit<EOL>

Return a recursive implementation of a multiplexor circuit,
where each instruction itself has a decomposition based on
smaller multiplexors.

The LSB is the multiplexor "data" and the other bits are multiplexor "select".

Args:
    target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed
        over all other "select" qubits
    list_of_angles (list[float]): list of rotation angles to apply Ry and Rz

Returns:
    DAGCircuit: the circuit implementing the multiplexor's action


q = QuantumRegister(self.num_qubits)<EOL>circuit = QuantumCircuit(q, name='<STR_LIT>')<EOL>remaining_param = self.params<EOL>for i in range(self.num_qubits):<EOL><INDENT>(remaining_param,<EOL>thetas,<EOL>phis) = Initialize._rotations_to_disentangle(remaining_param)<EOL>rz_mult = self._multiplex(RZGate, phis)<EOL>ry_mult = self._multiplex(RYGate, thetas)<EOL>circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits])<EOL>circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits])<EOL><DEDENT>return circuit<EOL>

Call to create a circuit with gates that take the
desired vector to zero.

Returns:
    QuantumCircuit: circuit to take self.params vector to |00..0>


@_to_bits(<NUM_LIT:2>)<EOL>@_op_expand(<NUM_LIT:2>)<EOL>def cu1(self, theta, ctl, tgt):

return self.append(Cu1Gate(theta), [ctl, tgt], [])<EOL>

Apply cu1 from ctl to tgt with angle theta.


super().__init__("<STR_LIT>", <NUM_LIT:2>, [theta])<EOL>


super().__init__("<STR_LIT>", <NUM_LIT:1>, [theta], label=label)<EOL>


@_to_bits(<NUM_LIT:1>)<EOL>@_op_expand(<NUM_LIT:1>)<EOL>def u2(self, phi, lam, q):

return self.append(U2Gate(phi, lam), [q], [])<EOL>


isqrt2 = <NUM_LIT:1> / numpy.sqrt(<NUM_LIT:2>)<EOL>phi, lam = self.params<EOL>phi, lam = float(phi), float(lam)<EOL>return numpy.array([[isqrt2, -numpy.exp(<NUM_LIT> * lam) * isqrt2],<EOL>[<EOL>numpy.exp(<NUM_LIT> * phi) * isqrt2,<EOL>numpy.exp(<NUM_LIT> * (phi + lam)) * isqrt2<EOL>]],<EOL>dtype=complex)<EOL>


return CrzGate(-self.params[<NUM_LIT:0>])<EOL>


return numpy.array([[<NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>]], dtype=complex)<EOL>


return HGate()<EOL>


return numpy.array([[<NUM_LIT:1>, <NUM_LIT:1>],<EOL>[<NUM_LIT:1>, -<NUM_LIT:1>]], dtype=complex) / numpy.sqrt(<NUM_LIT:2>)<EOL>


super().__init__("<STR_LIT:y>", <NUM_LIT:1>, [], label=label)<EOL>


return YGate()<EOL>


return numpy.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>

Return a Numpy.array for the Toffoli gate.


@_to_bits(<NUM_LIT:3>)<EOL>@_op_expand(<NUM_LIT:3>, broadcastable=[True, True, False])<EOL>def ccx(self, ctl1, ctl2, tgt):

return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])<EOL>

Apply Toffoli to from ctl1 and ctl2 to tgt.


theta, phi, lam = self.params<EOL>theta, phi, lam = float(theta), float(phi), float(lam)<EOL>return numpy.array(<EOL>[[<EOL>numpy.cos(theta / <NUM_LIT:2>),<EOL>-numpy.exp(<NUM_LIT> * lam) * numpy.sin(theta / <NUM_LIT:2>)<EOL>],<EOL>[<EOL>numpy.exp(<NUM_LIT> * phi) * numpy.sin(theta / <NUM_LIT:2>),<EOL>numpy.exp(<NUM_LIT> * (phi + lam)) * numpy.cos(theta / <NUM_LIT:2>)<EOL>]],<EOL>dtype=complex)<EOL>


@_to_bits(<NUM_LIT:2>)<EOL>@_op_expand(<NUM_LIT:2>)<EOL>def ch(self, ctl, tgt):

return self.append(CHGate(), [ctl, tgt], [])<EOL>


return CHGate()<EOL>


return self.append(IdGate(), [q], [])<EOL>


@_to_bits(<NUM_LIT:1>)<EOL>@_op_expand(<NUM_LIT:1>)<EOL>def rz(self, phi, q):

return self.append(RZGate(phi), [q], [])<EOL>


super().__init__("<STR_LIT>", <NUM_LIT:1>, [phi])<EOL>


super().__init__("<STR_LIT>", <NUM_LIT:3>, [])<EOL>


return Barrier(self.num_qubits)<EOL>


super().__init__("<STR_LIT:s>", <NUM_LIT:1>, [], label=label)<EOL>


return SdgGate()<EOL>


return self.append(SGate(), [q], [])<EOL>


return numpy.array([[<NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, -<NUM_LIT>]], dtype=complex)<EOL>


definition = []<EOL>q = QuantumRegister(<NUM_LIT:2>, "<STR_LIT:q>")<EOL>rule = [<EOL>(HGate(), [q[<NUM_LIT:1>]], []),<EOL>(CnotGate(), [q[<NUM_LIT:0>], q[<NUM_LIT:1>]], []),<EOL>(HGate(), [q[<NUM_LIT:1>]], [])<EOL>]<EOL>for inst in rule:<EOL><INDENT>definition.append(inst)<EOL><DEDENT>self.definition = definition<EOL>


@_to_bits(<NUM_LIT:2>)<EOL>@_op_expand(<NUM_LIT:2>)<EOL>def cx_base(self, ctl, tgt):

return self.append(CXBase(), [ctl, tgt], [])<EOL>


return RXGate(-self.params[<NUM_LIT:0>])<EOL>

Invert this gate.

        rx(theta)^dagger = rx(-theta)


return numpy.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>


@_to_bits(<NUM_LIT:2>)<EOL>@_op_expand(<NUM_LIT:2>)<EOL>def cx(self, ctl, tgt):

return self.append(CnotGate(), [ctl, tgt], [])<EOL>


return ZGate()<EOL>


super().__init__("<STR_LIT:z>", <NUM_LIT:1>, [], label=label)<EOL>


return self.append(ZGate(), [q], [])<EOL>


return numpy.array([[<NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, -<NUM_LIT:1>]], dtype=complex)<EOL>


super().__init__("<STR_LIT>", <NUM_LIT:1>, [theta])<EOL>


return TdgGate()<EOL>


<EOL>if not isinstance(label, str):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>label = str(label)<EOL><DEDENT>if isinstance(qubits, QuantumRegister):<EOL><INDENT>qubits = qubits[:]<EOL><DEDENT>if not qubits:<EOL><INDENT>tuples = []<EOL>if isinstance(self, QuantumCircuit):<EOL><INDENT>for register in self.qregs:<EOL><INDENT>tuples.append(register)<EOL><DEDENT><DEDENT>if not tuples:<EOL><INDENT>raise ExtensionError('<STR_LIT>')<EOL><DEDENT>qubits = []<EOL>for tuple_element in tuples:<EOL><INDENT>if isinstance(tuple_element, QuantumRegister):<EOL><INDENT>for j in range(tuple_element.size):<EOL><INDENT>qubits.append((tuple_element, j))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>qubits.append(tuple_element)<EOL><DEDENT><DEDENT><DEDENT>return self.append(<EOL>Snapshot(<EOL>label,<EOL>snapshot_type=snapshot_type,<EOL>num_qubits=len(qubits),<EOL>params=params), qubits)<EOL>

Take a statevector snapshot of the internal simulator representation.
    Works on all qubits, and prevents reordering (like barrier).

    For other types of snapshots use the Snapshot extension directly.

    Args:
        label (str): a snapshot label to report the result
        snapshot_type (str): the type of the snapshot.
        qubits (list or None): the qubits to apply snapshot to [Default: None].
        params (list or None): the parameters for snapshot_type [Default: None].

    Returns:
        QuantumCircuit: with attached command

    Raises:
        ExtensionError: malformed command


if not isinstance(label, str):<EOL><INDENT>raise ExtensionError('<STR_LIT>')<EOL><DEDENT>self._label = label<EOL>self._snapshot_type = snapshot_type<EOL>if params is None:<EOL><INDENT>params = []<EOL><DEDENT>super().__init__('<STR_LIT>', num_qubits, num_clbits, params)<EOL>

Create new snapshot instruction.

        Args:
            label (str): the snapshot label for result data.
            snapshot_type (str): the type of the snapshot.
            num_qubits (int): the number of qubits for the snapshot type [Default: 0].
            num_clbits (int): the number of classical bits for the snapshot type [Default: 0].
            params (list or None): the parameters for snapshot_type [Default: None].

        Raises:
            ExtensionError: if snapshot label is invalid.


instruction = super().assemble()<EOL>instruction.label = self._label<EOL>instruction.snapshot_type = self._snapshot_type<EOL>return instruction<EOL>


if os.getenv('<STR_LIT>'):<EOL><INDENT>if os.getenv('<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif os.getenv('<STR_LIT>'):<EOL><INDENT>if os.getenv('<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Check if the tests are being run in a CI environment from a PR.

    Check if the tests are being run in a CI environment and if it is a pull
    request.

    Returns:
        bool: True if the tests are executed inside a CI tool, and the changes
            are not against the "master" branch.


return [response for response, request in<EOL>zip(cassette_dict['<STR_LIT>'], cassette_dict['<STR_LIT>'])<EOL>if string_to_find in request.path]<EOL>

Filters the requests from cassette_dict

        Args:
            string_to_find (str): request path
            cassette_dict (dict): a VCR cassette dictionary

        Returns:
            Request: VCR's representation of a request.


header_list = []<EOL>for item in headers:<EOL><INDENT>if not isinstance(item, tuple):<EOL><INDENT>item = (item, None)<EOL><DEDENT>header_list.append(item[<NUM_LIT:0>:<NUM_LIT:2>])  <EOL><DEDENT>def before_record_response_cb(response):<EOL><INDENT>"""<STR_LIT>"""<EOL>for (header, value) in header_list:<EOL><INDENT>with suppress(KeyError):<EOL><INDENT>if value:<EOL><INDENT>response['<STR_LIT>'][header] = value<EOL><DEDENT>else:<EOL><INDENT>del response['<STR_LIT>'][header]<EOL><DEDENT><DEDENT><DEDENT>return response<EOL><DEDENT>return before_record_response_cb<EOL>

Remove headers from the response.

    Args:
        headers (list): headers to remove from the response

    Returns:
        callable: for been used in before_record_response VCR constructor.


@staticmethod<EOL><INDENT>def get_new_id(field, path, id_tracker, type_=str):<DEDENT>

if type_ == float:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if type_ == int:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>dummy_name = '<STR_LIT>' % (path.replace('<STR_LIT:/>', '<STR_LIT>'), field)<EOL>count = len(list(filter(lambda x: str(x).startswith(dummy_name), id_tracker.values())))<EOL>return "<STR_LIT>" % (dummy_name, count + <NUM_LIT:1>)<EOL>

Creates a new dummy id (or value) for replacing an existing id (or value).

        Args:
            field (str): field name is used, in same cases, to create a dummy value.
            path (str): path of the request is used, in same cases, to create a dummy value.
            id_tracker (dict): a map of already assigned ids and generated ids.
            type_ (type): type of the value.

        Returns:
            str: that is used to replace a value.


cmap = [[<NUM_LIT:1>, <NUM_LIT:0>], [<NUM_LIT:2>, <NUM_LIT:0>], [<NUM_LIT:2>, <NUM_LIT:1>], [<NUM_LIT:3>, <NUM_LIT:2>], [<NUM_LIT:3>, <NUM_LIT:4>], [<NUM_LIT:4>, <NUM_LIT:2>]]<EOL>configuration = BackendConfiguration(<EOL>backend_name='<STR_LIT>',<EOL>backend_version='<STR_LIT>',<EOL>n_qubits=<NUM_LIT:5>,<EOL>basis_gates=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:id>'],<EOL>simulator=False,<EOL>local=True,<EOL>conditional=False,<EOL>open_pulse=False,<EOL>memory=False,<EOL>max_shots=<NUM_LIT>,<EOL>gates=[GateConfig(name='<STR_LIT>', parameters=[], qasm_def='<STR_LIT>')],<EOL>coupling_map=cmap,<EOL>)<EOL>super().__init__(configuration)<EOL>


qr = QuantumRegister(<NUM_LIT:2>, name='<STR_LIT>')<EOL>qc = QuantumCircuit(qr, name='<STR_LIT>')<EOL>qc.h(qr[<NUM_LIT:0>])<EOL>qc.cx(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>return qc<EOL>


return self.provider_cls()<EOL>


<EOL>if sys.platform == '<STR_LIT>':<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>import qiskit.providers.aer  <EOL><DEDENT>except ImportError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Check if the C++ simulator can be instantiated.

    Returns:
        bool: True if simulator executable is available


warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>return synthesis.two_qubit_kak(unitary_matrix)<EOL>


super().__init__(*msg)<EOL>self.msg = '<STR_LIT:U+0020>'.join(msg)<EOL>


<EOL>html_template = Template("""<STR_LIT>""")<EOL>javascript_template = Template("""<STR_LIT>""")<EOL>rho = _validate_input_state(rho)<EOL>if figsize is None:<EOL><INDENT>options = {}<EOL><DEDENT>else:<EOL><INDENT>options = {'<STR_LIT:width>': figsize[<NUM_LIT:0>], '<STR_LIT>': figsize[<NUM_LIT:1>]}<EOL><DEDENT>div_number = str(time.time())<EOL>div_number = re.sub('<STR_LIT>', '<STR_LIT>', div_number)<EOL>real = []<EOL>imag = []<EOL>for xvalue in rho:<EOL><INDENT>row_real = []<EOL>col_imag = []<EOL>for value_real in xvalue.real:<EOL><INDENT>row_real.append(float(value_real))<EOL><DEDENT>real.append(row_real)<EOL>for value_imag in xvalue.imag:<EOL><INDENT>col_imag.append(float(value_imag))<EOL><DEDENT>imag.append(col_imag)<EOL><DEDENT>html = html_template.substitute({<EOL>'<STR_LIT>': div_number<EOL>})<EOL>javascript = javascript_template.substitute({<EOL>'<STR_LIT>': div_number,<EOL>'<STR_LIT>': [{'<STR_LIT:data>': real}, {'<STR_LIT:data>': imag}],<EOL>'<STR_LIT>': options<EOL>})<EOL>display(HTML(html + javascript))<EOL>

Create a hinton representation.

        Graphical representation of the input array using a 2D city style
        graph (hinton).

        Args:
            rho (array): Density matrix
            figsize (tuple): Figure size in pixels.


<EOL>html_template = Template("""<STR_LIT>""")<EOL>javascript_template = Template("""<STR_LIT>""")<EOL>rho = _validate_input_state(rho)<EOL>if figsize is None:<EOL><INDENT>options = {}<EOL><DEDENT>else:<EOL><INDENT>options = {'<STR_LIT:width>': figsize[<NUM_LIT:0>], '<STR_LIT>': figsize[<NUM_LIT:1>]}<EOL><DEDENT>num = int(np.log2(len(rho)))<EOL>bloch_data = []<EOL>for i in range(num):<EOL><INDENT>pauli_singles = [Pauli.pauli_single(num, i, '<STR_LIT:X>'), Pauli.pauli_single(num, i, '<STR_LIT:Y>'),<EOL>Pauli.pauli_single(num, i, '<STR_LIT>')]<EOL>bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),<EOL>pauli_singles))<EOL>bloch_data.append(bloch_state)<EOL><DEDENT>div_number = str(time.time())<EOL>div_number = re.sub('<STR_LIT>', '<STR_LIT>', div_number)<EOL>html = html_template.substitute({<EOL>'<STR_LIT>': div_number<EOL>})<EOL>javascript = javascript_template.substitute({<EOL>'<STR_LIT:data>': bloch_data,<EOL>'<STR_LIT>': div_number,<EOL>'<STR_LIT>': options<EOL>})<EOL>display(HTML(html + javascript))<EOL>

Create a bloch sphere representation.

        Graphical representation of the input array, using as much bloch
        spheres as qubit are required.

        Args:
            rho (array): State vector or density matrix
            figsize (tuple): Figure size in pixels.


<EOL>html_template = Template("""<STR_LIT>""")<EOL>javascript_template = Template("""<STR_LIT>""")<EOL>rho = _validate_input_state(rho)<EOL>if figsize is None:<EOL><INDENT>options = {}<EOL><DEDENT>else:<EOL><INDENT>options = {'<STR_LIT:width>': figsize[<NUM_LIT:0>], '<STR_LIT>': figsize[<NUM_LIT:1>]}<EOL><DEDENT>qspheres_data = []<EOL>num = int(np.log2(len(rho)))<EOL>weig, stateall = linalg.eigh(rho)<EOL>for _ in range(<NUM_LIT:2>**num):<EOL><INDENT>probmix = weig.max()<EOL>prob_location = weig.argmax()<EOL>if probmix > <NUM_LIT>:<EOL><INDENT>state = stateall[:, prob_location]<EOL>loc = np.absolute(state).argmax()<EOL>for j in range(<NUM_LIT:2>**num):<EOL><INDENT>test = np.absolute(np.absolute(state[j]) -<EOL>np.absolute(state[loc]))<EOL>if test < <NUM_LIT>:<EOL><INDENT>loc = j<EOL>break<EOL><DEDENT><DEDENT>angles = (np.angle(state[loc]) + <NUM_LIT:2> * np.pi) % (<NUM_LIT:2> * np.pi)<EOL>angleset = np.exp(-<NUM_LIT>*angles)<EOL>state = angleset*state<EOL>state.flatten()<EOL>spherepoints = []<EOL>for i in range(<NUM_LIT:2>**num):<EOL><INDENT>element = bin(i)[<NUM_LIT:2>:].zfill(num)<EOL>weight = element.count("<STR_LIT:1>")<EOL>number_of_divisions = n_choose_k(num, weight)<EOL>weight_order = bit_string_index(element)<EOL>angle = weight_order * <NUM_LIT:2> * np.pi / number_of_divisions<EOL>zvalue = -<NUM_LIT:2> * weight / num + <NUM_LIT:1><EOL>xvalue = np.sqrt(<NUM_LIT:1> - zvalue**<NUM_LIT:2>) * np.cos(angle)<EOL>yvalue = np.sqrt(<NUM_LIT:1> - zvalue**<NUM_LIT:2>) * np.sin(angle)<EOL>prob = np.real(np.dot(state[i], state[i].conj()))<EOL>angles = (np.angle(state[i]) + <NUM_LIT:2> * np.pi) % (<NUM_LIT:2> * np.pi)<EOL>qpoint = {<EOL>'<STR_LIT:x>': xvalue,<EOL>'<STR_LIT:y>': yvalue,<EOL>'<STR_LIT:z>': zvalue,<EOL>'<STR_LIT>': prob,<EOL>'<STR_LIT>': angles<EOL>}<EOL>spherepoints.append(qpoint)<EOL><DEDENT>sphere = {<EOL>'<STR_LIT>': spherepoints,<EOL>'<STR_LIT>': probmix<EOL>}<EOL>qspheres_data.append(sphere)<EOL>weig[prob_location] = <NUM_LIT:0><EOL><DEDENT><DEDENT>div_number = str(time.time())<EOL>div_number = re.sub('<STR_LIT>', '<STR_LIT>', div_number)<EOL>html = html_template.substitute({<EOL>'<STR_LIT>': div_number<EOL>})<EOL>javascript = javascript_template.substitute({<EOL>'<STR_LIT:data>': qspheres_data,<EOL>'<STR_LIT>': div_number,<EOL>'<STR_LIT>': options<EOL>})<EOL>display(HTML(html + javascript))<EOL>

Create a Q sphere representation.

        Graphical representation of the input array, using a Q sphere for each
        eigenvalue.

        Args:
            rho (array): State vector or density matrix.
            figsize (tuple): Figure size in pixels.


n = len(text)<EOL>k = text.count("<STR_LIT:1>")<EOL>if text.count("<STR_LIT:0>") != n - k:<EOL><INDENT>raise VisualizationError("<STR_LIT>")<EOL><DEDENT>ones = [pos for pos, char in enumerate(text) if char == "<STR_LIT:1>"]<EOL>return lex_index(n, k, ones)<EOL>

Return the index of a string of 0s and 1s.


def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False):

<EOL>html_template = Template("""<STR_LIT>""")<EOL>javascript_template = Template("""<STR_LIT>""")<EOL>rho = _validate_input_state(rho)<EOL>if figsize is None:<EOL><INDENT>figsize = (<NUM_LIT:7>, <NUM_LIT:5>)<EOL><DEDENT>options = {'<STR_LIT:width>': figsize[<NUM_LIT:0>], '<STR_LIT>': figsize[<NUM_LIT:1>],<EOL>'<STR_LIT>': int(slider), '<STR_LIT>': int(show_legend)}<EOL>div_number = str(time.time())<EOL>div_number = re.sub('<STR_LIT>', '<STR_LIT>', div_number)<EOL>data_to_plot = []<EOL>rho_data = process_data(rho)<EOL>data_to_plot.append(dict(<EOL>data=rho_data<EOL>))<EOL>html = html_template.substitute({<EOL>'<STR_LIT>': div_number<EOL>})<EOL>javascript = javascript_template.substitute({<EOL>'<STR_LIT>': div_number,<EOL>'<STR_LIT>': data_to_plot,<EOL>'<STR_LIT>': options<EOL>})<EOL>display(HTML(html + javascript))<EOL>

Create a paulivec representation.

        Graphical representation of the input array.

        Args:
            rho (array): State vector or density matrix.
            figsize (tuple): Figure size in pixels.
            slider (bool): activate slider
            show_legend (bool): show legend of graph content


result = dict()<EOL>if number_to_keep != <NUM_LIT:0>:<EOL><INDENT>data_temp = dict(Counter(data).most_common(number_to_keep))<EOL>data_temp['<STR_LIT>'] = sum(data.values()) - sum(data_temp.values())<EOL>data = data_temp<EOL><DEDENT>labels = data<EOL>values = np.array([data[key] for key in labels], dtype=float)<EOL>pvalues = values / sum(values)<EOL>for position, label in enumerate(labels):<EOL><INDENT>result[label] = round(pvalues[position], <NUM_LIT:5>)<EOL><DEDENT>return result<EOL>

Prepare received data for representation.

        Args:
            data (dict): values to represent (ex. {'001' : 130})
            number_to_keep (int): number of elements to show individually.

        Returns:
            dict: processed data to show.


def iplot_histogram(data, figsize=None, number_to_keep=None,<EOL>sort='<STR_LIT>', legend=None):

<EOL>html_template = Template("""<STR_LIT>""")<EOL>javascript_template = Template("""<STR_LIT>""")<EOL>div_number = str(time.time())<EOL>div_number = re.sub('<STR_LIT>', '<STR_LIT>', div_number)<EOL>if figsize is None:<EOL><INDENT>figsize = (<NUM_LIT:7>, <NUM_LIT:5>)<EOL><DEDENT>options = {'<STR_LIT>': <NUM_LIT:0> if number_to_keep is None else number_to_keep,<EOL>'<STR_LIT>': sort,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT:width>': int(figsize[<NUM_LIT:0>]),<EOL>'<STR_LIT>': int(figsize[<NUM_LIT:1>])}<EOL>if legend:<EOL><INDENT>options['<STR_LIT>'] = <NUM_LIT:1><EOL><DEDENT>data_to_plot = []<EOL>if isinstance(data, dict):<EOL><INDENT>data = [data]<EOL><DEDENT>if legend and len(legend) != len(data):<EOL><INDENT>raise VisualizationError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(len(legend), len(data)))<EOL><DEDENT>for item, execution in enumerate(data):<EOL><INDENT>exec_data = process_data(execution, options['<STR_LIT>'])<EOL>out_dict = {'<STR_LIT:data>': exec_data}<EOL>if legend:<EOL><INDENT>out_dict['<STR_LIT:name>'] = legend[item]<EOL><DEDENT>data_to_plot.append(out_dict)<EOL><DEDENT>html = html_template.substitute({<EOL>'<STR_LIT>': div_number<EOL>})<EOL>javascript = javascript_template.substitute({<EOL>'<STR_LIT>': div_number,<EOL>'<STR_LIT>': data_to_plot,<EOL>'<STR_LIT>': options<EOL>})<EOL>display(HTML(html + javascript))<EOL>

Create a histogram representation.

        Graphical representation of the input array using a vertical bars
        style graph.

        Args:
            data (list or dict):  This is either a list of dicts or a single
                dict containing the values to represent (ex. {'001' : 130})
            figsize (tuple): Figure size in pixels.
            number_to_keep (int): The number of terms to plot and
                rest is made into a single bar called other values
            sort (string): Could be 'asc' or 'desc'
            legend (list): A list of strings to use for labels of the data.
                The number of entries must match the length of data.
        Raises:
            VisualizationError: When legend is provided and the length doesn't
                match the input data.


def plot_bloch_multivector(rho, title='<STR_LIT>', figsize=None):

if not HAS_MATPLOTLIB:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>rho = _validate_input_state(rho)<EOL>num = int(np.log2(len(rho)))<EOL>width, height = plt.figaspect(<NUM_LIT:1>/num)<EOL>fig = plt.figure(figsize=(width, height))<EOL>for i in range(num):<EOL><INDENT>ax = fig.add_subplot(<NUM_LIT:1>, num, i + <NUM_LIT:1>, projection='<STR_LIT>')<EOL>pauli_singles = [<EOL>Pauli.pauli_single(num, i, '<STR_LIT:X>'),<EOL>Pauli.pauli_single(num, i, '<STR_LIT:Y>'),<EOL>Pauli.pauli_single(num, i, '<STR_LIT>')<EOL>]<EOL>bloch_state = list(<EOL>map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),<EOL>pauli_singles))<EOL>plot_bloch_vector(bloch_state, "<STR_LIT>" + str(i), ax=ax,<EOL>figsize=figsize)<EOL><DEDENT>fig.suptitle(title, fontsize=<NUM_LIT:16>)<EOL>plt.close(fig)<EOL>return fig<EOL>

Plot the Bloch sphere.

    Plot a sphere, axes, the Bloch vector, and its projections onto each axis.

    Args:
        rho (ndarray): Numpy array for state vector or density matrix.
        title (str): a string that represents the plot title
        figsize (tuple): Has no effect, here for compatibility only.

    Returns:
        Figure: A matplotlib figure instance if `ax = None`.

    Raises:
        ImportError: Requires matplotlib.


angles = np.angle(complex_number)<EOL>angle_round = int(((angles + <NUM_LIT:2> * np.pi) % (<NUM_LIT:2> * np.pi))/np.pi*<NUM_LIT:6>)<EOL>color_map = {<EOL><NUM_LIT:0>: (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>),  <EOL><NUM_LIT:1>: (<NUM_LIT:0.5>, <NUM_LIT:0>, <NUM_LIT:1>),  <EOL><NUM_LIT:2>: (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),  <EOL><NUM_LIT:3>: (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0.5>),  <EOL><NUM_LIT:4>: (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>),  <EOL><NUM_LIT:5>: (<NUM_LIT:1>, <NUM_LIT:0.5>, <NUM_LIT:0>),  <EOL><NUM_LIT:6>: (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>),  <EOL><NUM_LIT:7>: (<NUM_LIT:0.5>, <NUM_LIT:1>, <NUM_LIT:0>),  <EOL><NUM_LIT:8>: (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),  <EOL><NUM_LIT:9>: (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0.5>),  <EOL><NUM_LIT:10>: (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>),  <EOL><NUM_LIT:11>: (<NUM_LIT:0>, <NUM_LIT:0.5>, <NUM_LIT:1>)  <EOL>}<EOL>return color_map[angle_round]<EOL>

Map a phase of a complexnumber to a color in (r,g,b).

    complex_number is phase is first mapped to angle in the range
    [0, 2pi] and then to a color wheel with blue at zero phase.


def plot_state(quantum_state, method='<STR_LIT>', figsize=None):

if not HAS_MATPLOTLIB:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>warnings.warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>rho = _validate_input_state(quantum_state)<EOL>fig = None<EOL>if method == '<STR_LIT>':<EOL><INDENT>fig = plot_state_city(rho, figsize=figsize)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>fig = plot_state_paulivec(rho, figsize=figsize)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>fig = plot_state_qsphere(rho, figsize=figsize)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>plot_bloch_multivector(rho, figsize=figsize)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>fig = plot_state_hinton(rho, figsize=figsize)<EOL><DEDENT>return fig<EOL>

Plot the quantum state.

    Args:
        quantum_state (ndarray): statevector or density matrix
                                 representation of a quantum state.
        method (str): Plotting method to use.
        figsize (tuple): Figure size in inches,

    Returns:
         matplotlib.Figure: The matplotlib.Figure of the visualization
    Raises:
        ImportError: Requires matplotlib.
        VisualizationError: if the input is not a statevector or density
        matrix, or if the state is not an multi-qubit quantum state.


if isinstance(polygons, np.ndarray):<EOL><INDENT>n = polygons.shape[-<NUM_LIT:2>]<EOL>i1, i2, i3 = <NUM_LIT:0>, n//<NUM_LIT:3>, <NUM_LIT:2>*n//<NUM_LIT:3><EOL>v1 = polygons[..., i1, :] - polygons[..., i2, :]<EOL>v2 = polygons[..., i2, :] - polygons[..., i3, :]<EOL><DEDENT>else:<EOL><INDENT>v1 = np.empty((len(polygons), <NUM_LIT:3>))<EOL>v2 = np.empty((len(polygons), <NUM_LIT:3>))<EOL>for poly_i, ps in enumerate(polygons):<EOL><INDENT>n = len(ps)<EOL>i1, i2, i3 = <NUM_LIT:0>, n//<NUM_LIT:3>, <NUM_LIT:2>*n//<NUM_LIT:3><EOL>v1[poly_i, :] = ps[i1, :] - ps[i2, :]<EOL>v2[poly_i, :] = ps[i2, :] - ps[i3, :]<EOL><DEDENT><DEDENT>return np.cross(v1, v2)<EOL>

Takes a list of polygons and return an array of their normals.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon.
This normal of course might not make sense for polygons with more than
three points not lying in a plane, but it's a plausible and fast
approximation.
Args:
    polygons (list): list of (M_i, 3) array_like, or (..., M, 3) array_like
        A sequence of polygons to compute normals for, which can have
        varying numbers of vertices. If the polygons all have the same
        number of vertices and array is passed, then the operation will
        be vectorized.
Returns:
    normals: (..., 3) array_like
        A normal vector estimated for the polygon.


@staticmethod<EOL><INDENT>def fillup_layer(names):  <DEDENT>

longest = max([len(name) for name in names])<EOL>inputs_wires = []<EOL>for name in names:<EOL><INDENT>inputs_wires.append(InputWire(name.rjust(longest)))<EOL><DEDENT>return inputs_wires<EOL>

Creates a layer with InputWire elements.
Args:
    names (list): List of names for the wires.

Returns:
    list: The new layer


def _instruction_to_gate(self, instruction, layer):

current_cons = []<EOL>connection_label = None<EOL>def add_connected_gate(instruction, gates, layer, current_cons):<EOL><INDENT>for i, gate in enumerate(gates):<EOL><INDENT>layer.set_qubit(instruction.qargs[i], gate)<EOL>actual_index = self.qregs.index(instruction.qargs[i])<EOL>current_cons.append((actual_index, gate))<EOL><DEDENT><DEDENT>if instruction.name == '<STR_LIT>':<EOL><INDENT>gate = MeasureFrom()<EOL>layer.set_qubit(instruction.qargs[<NUM_LIT:0>], gate)<EOL>layer.set_clbit(instruction.cargs[<NUM_LIT:0>], MeasureTo())<EOL><DEDENT>elif instruction.name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>if not self.plotbarriers:<EOL><INDENT>return layer, current_cons, connection_label<EOL><DEDENT>for qubit in instruction.qargs:<EOL><INDENT>layer.set_qubit(qubit, Barrier())<EOL><DEDENT><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>gates = [Ex() for _ in range(len(instruction.qargs))]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>gates = [Bullet(), Ex(), Ex()]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>layer.set_qubit(instruction.qargs[<NUM_LIT:0>], Reset())<EOL><DEDENT>elif instruction.condition is not None:<EOL><INDENT>cllabel = TextDrawing.label_for_conditional(instruction)<EOL>qulabel = TextDrawing.label_for_box(instruction)<EOL>layer.set_cl_multibox(instruction.condition[<NUM_LIT:0>], cllabel, top_connect='<STR_LIT>')<EOL>layer.set_qubit(instruction.qargs[<NUM_LIT:0>], BoxOnQuWire(qulabel, bot_connect='<STR_LIT>'))<EOL><DEDENT>elif instruction.name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>gates = [Bullet() for _ in range(len(instruction.qargs) - <NUM_LIT:1>)]<EOL>gates.append(BoxOnQuWire('<STR_LIT:X>'))<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>gates = [Bullet(), BoxOnQuWire('<STR_LIT:Y>')]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>gates = [Bullet(), Bullet()]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>gates = [Bullet(), BoxOnQuWire('<STR_LIT:H>')]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>connection_label = TextDrawing.params_for_label(instruction)[<NUM_LIT:0>]<EOL>gates = [Bullet(), Bullet()]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>connection_label = "<STR_LIT>" % TextDrawing.params_for_label(instruction)[<NUM_LIT:0>]<EOL>gates = [Bullet(), Bullet()]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>params = TextDrawing.params_for_label(instruction)<EOL>gates = [Bullet(), BoxOnQuWire("<STR_LIT>" % '<STR_LIT:U+002C>'.join(params))]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif instruction.name == '<STR_LIT>':<EOL><INDENT>label = "<STR_LIT>" % TextDrawing.params_for_label(instruction)[<NUM_LIT:0>]<EOL>gates = [Bullet(), BoxOnQuWire(label)]<EOL>add_connected_gate(instruction, gates, layer, current_cons)<EOL><DEDENT>elif len(instruction.qargs) == <NUM_LIT:1> and not instruction.cargs:<EOL><INDENT>layer.set_qubit(instruction.qargs[<NUM_LIT:0>],<EOL>BoxOnQuWire(TextDrawing.label_for_box(instruction)))<EOL><DEDENT>elif len(instruction.qargs) >= <NUM_LIT:2> and not instruction.cargs:<EOL><INDENT>label = instruction.name<EOL>params = TextDrawing.params_for_label(instruction)<EOL>if params:<EOL><INDENT>label += "<STR_LIT>" % '<STR_LIT:U+002C>'.join(params)<EOL><DEDENT>layer.set_qu_multibox(instruction.qargs, label)<EOL><DEDENT>else:<EOL><INDENT>raise VisualizationError(<EOL>"<STR_LIT>", instruction)<EOL><DEDENT>current_cons.sort(key=lambda tup: tup[<NUM_LIT:0>])<EOL>current_cons = [g for q, g in current_cons]<EOL>return layer, current_cons, connection_label<EOL>

Convert an instruction into its corresponding Gate object, and establish
        any connections it introduces between qubits


return self.qubit_layer + self.clbit_layer<EOL>

Returns the composition of qubits and classic wires.
Returns:
    String: self.qubit_layer + self.clbit_layer


lines = []<EOL>bot_line = None<EOL>for wire in wires:<EOL><INDENT>top_line = '<STR_LIT>'<EOL>for instruction in wire:<EOL><INDENT>top_line += instruction.top<EOL><DEDENT>if bot_line is None:<EOL><INDENT>lines.append(top_line)<EOL><DEDENT>else:<EOL><INDENT>if vertically_compressed:<EOL><INDENT>lines.append(TextDrawing.merge_lines(lines.pop(), top_line))<EOL><DEDENT>else:<EOL><INDENT>lines.append(TextDrawing.merge_lines(lines[-<NUM_LIT:1>], top_line, icod="<STR_LIT>"))<EOL><DEDENT><DEDENT>mid_line = '<STR_LIT>'<EOL>for instruction in wire:<EOL><INDENT>mid_line += instruction.mid<EOL><DEDENT>lines.append(TextDrawing.merge_lines(lines[-<NUM_LIT:1>], mid_line, icod="<STR_LIT>"))<EOL>bot_line = '<STR_LIT>'<EOL>for instruction in wire:<EOL><INDENT>bot_line += instruction.bot<EOL><DEDENT>lines.append(TextDrawing.merge_lines(lines[-<NUM_LIT:1>], bot_line, icod="<STR_LIT>"))<EOL><DEDENT>return lines<EOL>

Given a list of wires, creates a list of lines with the text drawing.
Args:
    wires (list): A list of wires with instructions.
    vertically_compressed (bool): Default is `True`. It merges the lines
                             so the drawing will take less vertical room.
Returns:
    list: A list of lines with the text drawing.


def center_label(self, input_length, order):

location_in_the_box = '<STR_LIT:*>'.center(input_length * <NUM_LIT:2> - <NUM_LIT:1>).index('<STR_LIT:*>') + <NUM_LIT:1><EOL>top_limit = order * <NUM_LIT:2> + <NUM_LIT:2><EOL>bot_limit = top_limit + <NUM_LIT:2><EOL>if top_limit <= location_in_the_box < bot_limit:<EOL><INDENT>if location_in_the_box == top_limit:<EOL><INDENT>self.top_connect = self.label<EOL><DEDENT>elif location_in_the_box == top_limit + <NUM_LIT:1>:<EOL><INDENT>self.mid_content = self.label<EOL><DEDENT>else:<EOL><INDENT>self.bot_connect = self.label<EOL><DEDENT><DEDENT>

In multi-bit elements, the label is centered vertically.
Args:
    input_length (int): Rhe amount of wires affected.
    order (int): Which middle element is this one?


return "<STR_LIT:\n>".join(self.lines())<EOL>

Creates a long string with the ascii art
Returns:
    str: The lines joined by '\n'


return max(len(self.top), len(self.mid), len(self.bot))<EOL>

Returns the length of the element, including the box around.


wire_names = self.wire_names(with_initial_value=True)<EOL>if not wire_names:<EOL><INDENT>return []<EOL><DEDENT>layers = [InputWire.fillup_layer(wire_names)]<EOL>for instruction_layer in self.instructions:<EOL><INDENT>layer = Layer(self.qregs, self.cregs)<EOL>for instruction in instruction_layer:<EOL><INDENT>layer, current_connections, connection_label =self._instruction_to_gate(instruction, layer)<EOL>layer.connections.append((connection_label, current_connections))<EOL>layer.connect_with("<STR_LIT>")<EOL><DEDENT>layers.append(layer.full_layer)<EOL><DEDENT>return layers<EOL>

Constructs layers.
Returns:
    list: List of DrawElements.
Raises:
    VisualizationError: When the drawing is, for some reason, impossible to be drawn.


if self._width:<EOL><INDENT>return self._width<EOL><DEDENT>return len(self.mid_content)<EOL>

Returns the width of the label, including padding


def pulse_drawer(samples, duration, dt=None, interp_method='<STR_LIT:None>',<EOL>filename=None, interactive=False,<EOL>dpi=<NUM_LIT>, nop=<NUM_LIT:1000>, size=(<NUM_LIT:6>, <NUM_LIT:5>)):

try:<EOL><INDENT>from matplotlib import pyplot as plt<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if dt:<EOL><INDENT>_dt = dt<EOL><DEDENT>else:<EOL><INDENT>_dt = <NUM_LIT:1><EOL><DEDENT>re_y = np.real(samples)<EOL>im_y = np.imag(samples)<EOL>image = plt.figure(figsize=size)<EOL>ax0 = image.add_subplot(<NUM_LIT>)<EOL>if interp_method == '<STR_LIT>':<EOL><INDENT>time = np.arange(<NUM_LIT:0>, duration + <NUM_LIT:1>) * _dt + <NUM_LIT:0.5> * _dt<EOL>cs_ry = CubicSpline(time[:-<NUM_LIT:1>], re_y)<EOL>cs_iy = CubicSpline(time[:-<NUM_LIT:1>], im_y)<EOL>_time = np.linspace(<NUM_LIT:0>, duration * _dt, nop)<EOL>_re_y = cs_ry(_time)<EOL>_im_y = cs_iy(_time)<EOL><DEDENT>elif interp_method == '<STR_LIT:None>':<EOL><INDENT>time = np.arange(<NUM_LIT:0>, duration + <NUM_LIT:1>) * _dt<EOL>_time = np.r_[time[<NUM_LIT:0>], np.repeat(time[<NUM_LIT:1>:-<NUM_LIT:1>], <NUM_LIT:2>), time[-<NUM_LIT:1>]]<EOL>_re_y = np.repeat(re_y, <NUM_LIT:2>)<EOL>_im_y = np.repeat(im_y, <NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>' % interp_method)<EOL><DEDENT>ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time),<EOL>facecolor='<STR_LIT>', alpha=<NUM_LIT>,<EOL>edgecolor='<STR_LIT>', linewidth=<NUM_LIT>,<EOL>label='<STR_LIT>')<EOL>ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time),<EOL>facecolor='<STR_LIT>', alpha=<NUM_LIT>,<EOL>edgecolor='<STR_LIT>', linewidth=<NUM_LIT>,<EOL>label='<STR_LIT>')<EOL>ax0.set_xlim(<NUM_LIT:0>, duration * _dt)<EOL>ax0.grid(b=True, linestyle='<STR_LIT:->')<EOL>ax0.legend(bbox_to_anchor=(<NUM_LIT:0.5>, <NUM_LIT>), loc='<STR_LIT>',<EOL>ncol=<NUM_LIT:2>, frameon=False, fontsize=<NUM_LIT>)<EOL>if filename:<EOL><INDENT>image.savefig(filename, dpi=dpi, bbox_inches='<STR_LIT>')<EOL><DEDENT>plt.close(image)<EOL>if image and interactive:<EOL><INDENT>plt.show(image)<EOL><DEDENT>return image<EOL>

Plot the interpolated envelope of pulse

    Args:
        samples (ndarray): Data points of complex pulse envelope.
        duration (int): Pulse length (number of points).
        dt (float): Time interval of samples.
        interp_method (str): Method of interpolation
            (set `None` for turn off the interpolation).
        filename (str): Name required to save pulse image.
        interactive (bool): When set true show the circuit in a new window
            (this depends on the matplotlib backend being used supporting this).
        dpi (int): Resolution of saved image.
        nop (int): Data points for interpolation.
        size (tuple): Size of figure.
    Returns:
        matplotlib.figure: A matplotlib figure object for the pulse envelope.
    Raises:
        ImportError: when the output methods requieres non-installed libraries.
        QiskitError: when invalid interpolation method is specified.


self.points = []<EOL>self.vectors = []<EOL>self.point_style = []<EOL>self.annotations = []<EOL>


if isinstance(vectors[<NUM_LIT:0>], (list, np.ndarray)):<EOL><INDENT>for vec in vectors:<EOL><INDENT>self.vectors.append(vec)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.vectors.append(vectors)<EOL><DEDENT>

Add a list of vectors to Bloch sphere.

        Args:
            vectors (array_like):
                Array with vectors of unit length or smaller.


self.render(title=title)<EOL>if self.fig:<EOL><INDENT>plt.show(self.fig)<EOL><DEDENT>

Display Bloch sphere and corresponding data sets.


min_index = len(qregs)<EOL>max_index = <NUM_LIT:0><EOL>for qreg in instruction.qargs:<EOL><INDENT>index = qregs.index(qreg)<EOL>if index < min_index:<EOL><INDENT>min_index = index<EOL><DEDENT>if index > max_index:<EOL><INDENT>max_index = index<EOL><DEDENT><DEDENT>if instruction.cargs:<EOL><INDENT>return qregs[min_index:]<EOL><DEDENT>return qregs[min_index:max_index + <NUM_LIT:1>]<EOL>

Get the list of qubits drawing this gate would cover


if matchobj.group(<NUM_LIT:0>):<EOL><INDENT>return format(float(matchobj.group(<NUM_LIT:0>)), format_str)<EOL><DEDENT>return '<STR_LIT>'<EOL>

Truncate long floats

    Args:
        matchobj (re.Match): contains original float
        format_str (str): format specifier
    Returns:
       str: returns truncated float


max_column_widths = []<EOL>for layer in self.ops:<EOL><INDENT>current_max = <NUM_LIT:0><EOL>for op in layer:<EOL><INDENT>arg_str_len = <NUM_LIT:0><EOL>for arg in op.op.params:<EOL><INDENT>arg_str = re.sub(r'<STR_LIT>',<EOL>_truncate_float, str(arg))<EOL>arg_str_len += len(arg_str)<EOL><DEDENT>current_max = max(arg_str_len, current_max)<EOL><DEDENT>max_column_widths.append(current_max)<EOL><DEDENT>columns = <NUM_LIT:2><EOL>columns += len(self.ops)<EOL>sum_column_widths = sum(<NUM_LIT:1> + v / <NUM_LIT:3> for v in max_column_widths)<EOL>return columns, math.ceil(sum_column_widths) + <NUM_LIT:4><EOL>

Get depth information for the circuit.

        Returns:
            int: number of columns in the circuit
            int: total size of columns in the circuit


for i, bit in enumerate(self.qubit_list):<EOL><INDENT>if qubit == bit:<EOL><INDENT>qindex = i<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.VisualizationError("<STR_LIT>")<EOL><DEDENT>return qindex<EOL>

Get the index number for a quantum bit
        Args:
            qubit (tuple): The tuple of the bit of the form
                (register_name, bit_number)
        Returns:
            int: The index in the bit list
        Raises:
            VisualizationError: If the bit isn't found