Instruction:
How would you implement a function in Python 3 that
gives a circuit return a tuple of qregs cregs and ops that are layered.

Response:
def _get_layered_instructions(circuit, reverse_bits=False, justify=None):
    """
    Given a circuit, return a tuple (qregs, cregs, ops) where
    qregs and cregs are the quantum and classical registers
    in order (based on reverse_bits) and ops is a list
    of DAG nodes which type is "operation".
    Args:
        circuit (QuantumCircuit): From where the information is extracted.
        reverse_bits (bool): If true the order of the bits in the registers is
            reversed.
        justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
            the circuit should be justified.
    Returns:
        Tuple(list,list,list): To be consumed by the visualizer directly.
    """
    if justify:
        justify = justify.lower()

    # default to left
    justify = justify if justify in ('right', 'none') else 'left'

    dag = circuit_to_dag(circuit)
    ops = []
    qregs = []
    cregs = []

    for qreg in dag.qregs.values():
        qregs += [(qreg, bitno) for bitno in range(qreg.size)]

    for creg in dag.cregs.values():
        cregs += [(creg, bitno) for bitno in range(creg.size)]

    if justify == 'none':
        for node in dag.topological_op_nodes():
            ops.append([node])

    if justify == 'left':
        for dag_layer in dag.layers():
            layers = []
            current_layer = []

            dag_nodes = dag_layer['graph'].op_nodes()
            dag_nodes.sort(key=lambda nd: nd._node_id)

            for node in dag_nodes:
                multibit_gate = len(node.qargs) + len(node.cargs) > 1

                if multibit_gate:
                    # need to see if it crosses over any other nodes
                    gate_span = _get_gate_span(qregs, node)

                    all_indices = []
                    for check_node in dag_nodes:
                        if check_node != node:
                            all_indices += _get_gate_span(qregs, check_node)

                    if any(i in gate_span for i in all_indices):
                        # needs to be a new layer
                        layers.append([node])
                    else:
                        # can be added
                        current_layer.append(node)
                else:
                    current_layer.append(node)

            if current_layer:
                layers.append(current_layer)
            ops += layers

    if justify == 'right':
        dag_layers = []

        for dag_layer in dag.layers():
            dag_layers.append(dag_layer)

        # Have to work from the end of the circuit
        dag_layers.reverse()

        # Dict per layer, keys are qubits and values are the gate
        layer_dicts = [{}]

        for dag_layer in dag_layers:

            dag_instructions = dag_layer['graph'].op_nodes()

            # sort into the order they were input
            dag_instructions.sort(key=lambda nd: nd._node_id)
            for instruction_node in dag_instructions:

                gate_span = _get_gate_span(qregs, instruction_node)

                added = False
                for i in range(len(layer_dicts)):
                    # iterate from the end
                    curr_dict = layer_dicts[-1 - i]

                    if any(index in curr_dict for index in gate_span):
                        added = True

                        if i == 0:
                            new_dict = {}

                            for index in gate_span:
                                new_dict[index] = instruction_node
                            layer_dicts.append(new_dict)
                        else:
                            curr_dict = layer_dicts[-i]
                            for index in gate_span:
                                curr_dict[index] = instruction_node

                        break

                if not added:
                    for index in gate_span:
                        layer_dicts[0][index] = instruction_node

        # need to convert from dict format to layers
        layer_dicts.reverse()
        ops = [list(layer.values()) for layer in layer_dicts]

    if reverse_bits:
        qregs.reverse()
        cregs.reverse()

    return qregs, cregs, ops


Instruction:
Can you create a Python 3 function that
gets the list of qubits drawing this gate would cover

Response:
def _get_gate_span(qregs, instruction):
    """Get the list of qubits drawing this gate would cover"""

    min_index = len(qregs)
    max_index = 0
    for qreg in instruction.qargs:
        index = qregs.index(qreg)

        if index < min_index:
            min_index = index
        if index > max_index:
            max_index = index

    if instruction.cargs:
        return qregs[min_index:]

    return qregs[min_index:max_index + 1]


Instruction:
Given the following Python 3 function, write the documentation
def circuit_to_instruction(circuit):
    instruction = Instruction(name=circuit.name,
                              num_qubits=sum([qreg.size for qreg in circuit.qregs]),
                              num_clbits=sum([creg.size for creg in circuit.cregs]),
                              params=[])
    instruction.control = None

    def find_bit_position(bit):
        """find the index of a given bit (Register, int) within
        a flat ordered list of bits of the circuit
        """
        if isinstance(bit[0], QuantumRegister):
            ordered_regs = circuit.qregs
        else:
            ordered_regs = circuit.cregs
        reg_index = ordered_regs.index(bit[0])
        return sum([reg.size for reg in ordered_regs[:reg_index]]) + bit[1]

    definition = circuit.data.copy()

    if instruction.num_qubits > 0:
        q = QuantumRegister(instruction.num_qubits, 'q')
    if instruction.num_clbits > 0:
        c = ClassicalRegister(instruction.num_clbits, 'c')

    definition = list(map(lambda x:
                          (x[0],
                           list(map(lambda y: (q, find_bit_position(y)), x[1])),
                           list(map(lambda y: (c, find_bit_position(y)), x[2]))), definition))
    instruction.definition = definition

    return instruction

Response: Converts a QuantumCircuit to an Instruction object.


Instruction:
Can you write a function in Python 3 where it
runs the layout algorithm.

Response:
def run(self, dag):
        """
        Pick a convenient layout depending on the best matching
        qubit connectivity, and set the property `layout`.

        Args:
            dag (DAGCircuit): DAG to find layout for.

        Raises:
            TranspilerError: if dag wider than self.coupling_map
        """
        num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
        if num_dag_qubits > self.coupling_map.size():
            raise TranspilerError('Number of qubits greater than device.')
        best_sub = self._best_subset(num_dag_qubits)
        layout = Layout()
        map_iter = 0
        for qreg in dag.qregs.values():
            for i in range(qreg.size):
                layout[(qreg, i)] = int(best_sub[map_iter])
                map_iter += 1
        self.property_set['layout'] = layout


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _best_subset(self, n_qubits):
        if n_qubits == 1:
            return np.array([0])

        device_qubits = self.coupling_map.size()

        cmap = np.asarray(self.coupling_map.get_edges())
        data = np.ones_like(cmap[:, 0])
        sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
                                shape=(device_qubits, device_qubits)).tocsr()
        best = 0
        best_map = None
        # do bfs with each node as starting point
        for k in range(sp_cmap.shape[0]):
            bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
                                         return_predecessors=False)

            connection_count = 0
            sub_graph = []
            for i in range(n_qubits):
                node_idx = bfs[i]
                for j in range(sp_cmap.indptr[node_idx],
                               sp_cmap.indptr[node_idx + 1]):
                    node = sp_cmap.indices[j]
                    for counter in range(n_qubits):
                        if node == bfs[counter]:
                            connection_count += 1
                            sub_graph.append([node_idx, node])
                            break

            if connection_count > best:
                best = connection_count
                best_map = bfs[0:n_qubits]
                # Return a best mapping that has reduced bandwidth
                mapping = {}
                for edge in range(best_map.shape[0]):
                    mapping[best_map[edge]] = edge
                new_cmap = [[mapping[c[0]], mapping[c[1]]] for c in sub_graph]
                rows = [edge[0] for edge in new_cmap]
                cols = [edge[1] for edge in new_cmap]
                data = [1]*len(rows)
                sp_sub_graph = sp.coo_matrix((data, (rows, cols)),
                                             shape=(n_qubits, n_qubits)).tocsr()
                perm = cs.reverse_cuthill_mckee(sp_sub_graph)
                best_map = best_map[perm]
        return best_map

Response: Computes the qubit mapping with the best connectivity.


Instruction:
Write a Python 3 function for
returning True if completely - positive trace - preserving.

Response:
def is_cptp(self, atol=None, rtol=None):
        """Return True if completely-positive trace-preserving."""
        if self._data[1] is not None:
            return False
        if atol is None:
            atol = self._atol
        if rtol is None:
            rtol = self._rtol
        accum = 0j
        for op in self._data[0]:
            accum += np.dot(np.transpose(np.conj(op)), op)
        return is_identity_matrix(accum, rtol=rtol, atol=atol)


Instruction:
Write a Python 3 function for
returning the conjugate of the QuantumChannel.

Response:
def conjugate(self):
        """Return the conjugate of the QuantumChannel."""
        kraus_l, kraus_r = self._data
        kraus_l = [k.conj() for k in kraus_l]
        if kraus_r is not None:
            kraus_r = [k.conj() for k in kraus_r]
        return Kraus((kraus_l, kraus_r), self.input_dims(), self.output_dims())


Instruction:
Write a Python 3 script for
returning the transpose of the QuantumChannel.

Response:
def transpose(self):
        """Return the transpose of the QuantumChannel."""
        kraus_l, kraus_r = self._data
        kraus_l = [k.T for k in kraus_l]
        if kraus_r is not None:
            kraus_r = [k.T for k in kraus_r]
        return Kraus((kraus_l, kraus_r),
                     input_dims=self.output_dims(),
                     output_dims=self.input_dims())


Instruction:
How would you code a function in Python 3 to
return the composition of self and other.

Response:
def compose(self, other, qargs=None, front=False):
        """Return the composition channel self∘other.

        Args:
            other (QuantumChannel): a quantum channel subclass.
            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:
            Kraus: The composition channel as a Kraus object.

        Raises:
            QiskitError: if other cannot be converted to a channel, or
            has incompatible dimensions.
        """
        if qargs is not None:
            return Kraus(
                SuperOp(self).compose(other, qargs=qargs, front=front))

        if not isinstance(other, Kraus):
            other = Kraus(other)
        # Check dimensions match up
        if front and self._input_dim != other._output_dim:
            raise QiskitError(
                'input_dim of self must match output_dim of other')
        if not front and self._output_dim != other._input_dim:
            raise QiskitError(
                'input_dim of other must match output_dim of self')

        if front:
            ka_l, ka_r = self._data
            kb_l, kb_r = other._data
            input_dim = other._input_dim
            output_dim = self._output_dim
        else:
            ka_l, ka_r = other._data
            kb_l, kb_r = self._data
            input_dim = self._input_dim
            output_dim = other._output_dim

        kab_l = [np.dot(a, b) for a in ka_l for b in kb_l]
        if ka_r is None and kb_r is None:
            kab_r = None
        elif ka_r is None:
            kab_r = [np.dot(a, b) for a in ka_l for b in kb_r]
        elif kb_r is None:
            kab_r = [np.dot(a, b) for a in ka_r for b in kb_l]
        else:
            kab_r = [np.dot(a, b) for a in ka_r for b in kb_r]
        return Kraus((kab_l, kab_r), input_dim, output_dim)


Instruction:
Can you generate the documentation for the following Python 3 function
def power(self, n):
        if n > 0:
            return super().power(n)
        return Kraus(SuperOp(self).power(n))

Response: The matrix power of the superoperator matrix.


Instruction:
Can you implement a function in Python 3 that
returns the QuantumChannel self + other.

Response:
def multiply(self, other):
        """Return the QuantumChannel self + other.

        Args:
            other (complex): a complex number.

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

        Raises:
            QiskitError: if other is not a valid scalar.
        """
        if not isinstance(other, Number):
            raise QiskitError("other is not a number")
        # If the number is complex we need to convert to general
        # kraus channel so we multiply via Choi representation
        if isinstance(other, complex) or other < 0:
            # Convert to Choi-matrix
            return Kraus(Choi(self).multiply(other))
        # If the number is real we can update the Kraus operators
        # directly
        val = np.sqrt(other)
        kraus_r = None
        kraus_l = [val * k for k in self._data[0]]
        if self._data[1] is not None:
            kraus_r = [val * k for k in self._data[1]]
        return Kraus((kraus_l, kraus_r), self._input_dim, self._output_dim)


Instruction:
Can you generate the documentation for the following Python 3 function
def _evolve(self, state, qargs=None):
        # If subsystem evolution we use the SuperOp representation
        if qargs is not None:
            return SuperOp(self)._evolve(state, qargs)

        # Otherwise we compute full evolution directly
        state = self._format_state(state)
        if state.shape[0] != self._input_dim:
            raise QiskitError(
                "QuantumChannel input dimension is not equal to state dimension."
            )
        if state.ndim == 1 and self._data[1] is None and len(
                self._data[0]) == 1:
            # If we only have a single Kraus operator we can implement unitary-type
            # evolution of a state vector psi -> K[0].psi
            return np.dot(self._data[0][0], state)
        # Otherwise we always return a density matrix
        state = self._format_state(state, density_matrix=True)
        kraus_l, kraus_r = self._data
        if kraus_r is None:
            kraus_r = kraus_l
        return np.einsum('AiB,BC,AjC->ij', kraus_l, state,
                         np.conjugate(kraus_r))

Response: Evolve a state by the QuantumChannel.


Instruction:
Implement a Python 3 function for
returning the tensor product of self and other.

Response:
def _tensor_product(self, other, reverse=False):
        """Return the tensor product channel.

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

        Raises:
            QiskitError: if other cannot be converted to a channel.
        """
        # Convert other to Kraus
        if not isinstance(other, Kraus):
            other = Kraus(other)

        # Get tensor matrix
        ka_l, ka_r = self._data
        kb_l, kb_r = other._data
        if reverse:
            input_dims = self.input_dims() + other.input_dims()
            output_dims = self.output_dims() + other.output_dims()
            kab_l = [np.kron(b, a) for a in ka_l for b in kb_l]
        else:
            input_dims = other.input_dims() + self.input_dims()
            output_dims = other.output_dims() + self.output_dims()
            kab_l = [np.kron(a, b) for a in ka_l for b in kb_l]
        if ka_r is None and kb_r is None:
            kab_r = None
        else:
            if ka_r is None:
                ka_r = ka_l
            if kb_r is None:
                kb_r = kb_l
            if reverse:
                kab_r = [np.kron(b, a) for a in ka_r for b in kb_r]
            else:
                kab_r = [np.kron(a, b) for a in ka_r for b in kb_r]
        data = (kab_l, kab_r)
        return Kraus(data, input_dims, output_dims)


Instruction:
How would you implement a function in Python 3 that
returns the correspond floating point number.

Response:
def real(self, nested_scope=None):
        """Return the correspond floating point number."""
        operation = self.children[0].operation()
        lhs = self.children[1].real(nested_scope)
        rhs = self.children[2].real(nested_scope)
        return operation(lhs, rhs)


Instruction:
Here you have a function in Python 3, explain what it does
def sym(self, nested_scope=None):
        operation = self.children[0].operation()
        lhs = self.children[1].sym(nested_scope)
        rhs = self.children[2].sym(nested_scope)
        return operation(lhs, rhs)

Response: Return the correspond symbolic number.


Instruction:
Write a Python 3 script to
apply a barrier to all the qubits in that circuit.

Response:
def barrier(self, *qargs):
    """Apply barrier to circuit.
    If qargs is None, applies to all the qbits.
    Args is a list of QuantumRegister or single qubits.
    For QuantumRegister, applies barrier to all the qubits in that register."""
    qubits = []

    qargs = _convert_to_bits(qargs, [qbit for qreg in self.qregs for qbit in qreg])

    if not qargs:  # None
        for qreg in self.qregs:
            for j in range(qreg.size):
                qubits.append((qreg, j))

    for qarg in qargs:
        if isinstance(qarg, (QuantumRegister, list)):
            if isinstance(qarg, QuantumRegister):
                qubits.extend([(qarg, j) for j in range(qarg.size)])
            else:
                qubits.extend(qarg)
        else:
            qubits.append(qarg)

    return self.append(Barrier(len(qubits)), qubits, [])


Instruction:
Can you tell what is the following Python 3 function doing
def average_data(counts, observable):
    if not isinstance(observable, dict):
        observable = make_dict_observable(observable)
    temp = 0
    tot = sum(counts.values())
    for key in counts:
        if key in observable:
            temp += counts[key] * observable[key] / tot
    return temp

Response: Compute the mean value of an experiment and an observable.


Instruction:
Write a Python 3 script for
processing an Id or IndexedId node as a bit or register type.

Response:
def _process_bit_id(self, node):
        """Process an Id or IndexedId node as a bit or register type.

        Return a list of tuples (Register,index).
        """
        # pylint: disable=inconsistent-return-statements
        reg = None
        if node.name in self.dag.qregs:
            reg = self.dag.qregs[node.name]
        elif node.name in self.dag.cregs:
            reg = self.dag.cregs[node.name]
        else:
            raise QiskitError("expected qreg or creg name:",
                              "line=%s" % node.line,
                              "file=%s" % node.file)

        if node.type == "indexed_id":
            # An indexed bit or qubit
            return [(reg, node.index)]
        elif node.type == "id":
            # A qubit or qreg or creg
            if not self.bit_stack[-1]:
                # Global scope
                return [(reg, j) for j in range(reg.size)]
            else:
                # local scope
                if node.name in self.bit_stack[-1]:
                    return [self.bit_stack[-1][node.name]]
                raise QiskitError("expected local bit name:",
                                  "line=%s" % node.line,
                                  "file=%s" % node.file)
        return None


Instruction:
How would you explain what the following Python 3 function does
def _process_custom_unitary(self, node):
        name = node.name
        if node.arguments is not None:
            args = self._process_node(node.arguments)
        else:
            args = []
        bits = [self._process_bit_id(node_element)
                for node_element in node.bitlist.children]
        if name in self.gates:
            gargs = self.gates[name]["args"]
            gbits = self.gates[name]["bits"]
            # Loop over register arguments, if any.
            maxidx = max(map(len, bits))
            for idx in range(maxidx):
                self.arg_stack.append({gargs[j]: args[j]
                                       for j in range(len(gargs))})
                # Only index into register arguments.
                element = [idx*x for x in
                           [len(bits[j]) > 1 for j in range(len(bits))]]
                self.bit_stack.append({gbits[j]: bits[j][element[j]]
                                       for j in range(len(gbits))})
                self._create_dag_op(name,
                                    [self.arg_stack[-1][s].sym() for s in gargs],
                                    [self.bit_stack[-1][s] for s in gbits])
                self.arg_stack.pop()
                self.bit_stack.pop()
        else:
            raise QiskitError("internal error undefined gate:",
                              "line=%s" % node.line, "file=%s" % node.file)

Response: Process a custom unitary node.


Instruction:
Create a Python 3 function for
processing a gate node.

Response:
def _process_gate(self, node, opaque=False):
        """Process a gate node.

        If opaque is True, process the node as an opaque gate node.
        """
        self.gates[node.name] = {}
        de_gate = self.gates[node.name]
        de_gate["print"] = True  # default
        de_gate["opaque"] = opaque
        de_gate["n_args"] = node.n_args()
        de_gate["n_bits"] = node.n_bits()
        if node.n_args() > 0:
            de_gate["args"] = [element.name for element in node.arguments.children]
        else:
            de_gate["args"] = []
        de_gate["bits"] = [c.name for c in node.bitlist.children]
        if opaque:
            de_gate["body"] = None
        else:
            de_gate["body"] = node.body


Instruction:
Can you implement a function in Python 3 that
processes a CNOT gate node.

Response:
def _process_cnot(self, node):
        """Process a CNOT gate node."""
        id0 = self._process_bit_id(node.children[0])
        id1 = self._process_bit_id(node.children[1])
        if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1):
            raise QiskitError("internal error: qreg size mismatch",
                              "line=%s" % node.line, "file=%s" % node.file)
        maxidx = max([len(id0), len(id1)])
        for idx in range(maxidx):
            if len(id0) > 1 and len(id1) > 1:
                self.dag.apply_operation_back(CXBase(), [id0[idx], id1[idx]], [], self.condition)
            elif len(id0) > 1:
                self.dag.apply_operation_back(CXBase(), [id0[idx], id1[0]], [], self.condition)
            else:
                self.dag.apply_operation_back(CXBase(), [id0[0], id1[idx]], [], self.condition)


Instruction:
Write a Python 3 function that can
process a measurement node.

Response:
def _process_measure(self, node):
        """Process a measurement node."""
        id0 = self._process_bit_id(node.children[0])
        id1 = self._process_bit_id(node.children[1])
        if len(id0) != len(id1):
            raise QiskitError("internal error: reg size mismatch",
                              "line=%s" % node.line, "file=%s" % node.file)
        for idx, idy in zip(id0, id1):
            self.dag.apply_operation_back(Measure(), [idx], [idy], self.condition)


Instruction:
Write a Python 3 script to
process an if node.

Response:
def _process_if(self, node):
        """Process an if node."""
        creg_name = node.children[0].name
        creg = self.dag.cregs[creg_name]
        cval = node.children[1].value
        self.condition = (creg, cval)
        self._process_node(node.children[2])
        self.condition = None


Instruction:
Can you generate the documentation for the following Python 3 function
def _process_node(self, node):
        if node.type == "program":
            self._process_children(node)

        elif node.type == "qreg":
            qreg = QuantumRegister(node.index, node.name)
            self.dag.add_qreg(qreg)

        elif node.type == "creg":
            creg = ClassicalRegister(node.index, node.name)
            self.dag.add_creg(creg)

        elif node.type == "id":
            raise QiskitError("internal error: _process_node on id")

        elif node.type == "int":
            raise QiskitError("internal error: _process_node on int")

        elif node.type == "real":
            raise QiskitError("internal error: _process_node on real")

        elif node.type == "indexed_id":
            raise QiskitError("internal error: _process_node on indexed_id")

        elif node.type == "id_list":
            # We process id_list nodes when they are leaves of barriers.
            return [self._process_bit_id(node_children)
                    for node_children in node.children]

        elif node.type == "primary_list":
            # We should only be called for a barrier.
            return [self._process_bit_id(m) for m in node.children]

        elif node.type == "gate":
            self._process_gate(node)

        elif node.type == "custom_unitary":
            self._process_custom_unitary(node)

        elif node.type == "universal_unitary":
            args = self._process_node(node.children[0])
            qid = self._process_bit_id(node.children[1])
            for element in qid:
                self.dag.apply_operation_back(UBase(*args, element), self.condition)

        elif node.type == "cnot":
            self._process_cnot(node)

        elif node.type == "expression_list":
            return node.children

        elif node.type == "binop":
            raise QiskitError("internal error: _process_node on binop")

        elif node.type == "prefix":
            raise QiskitError("internal error: _process_node on prefix")

        elif node.type == "measure":
            self._process_measure(node)

        elif node.type == "format":
            self.version = node.version()

        elif node.type == "barrier":
            ids = self._process_node(node.children[0])
            qubits = []
            for qubit in ids:
                for j, _ in enumerate(qubit):
                    qubits.append(qubit[j])
            self.dag.apply_operation_back(Barrier(len(qubits)), qubits, [])

        elif node.type == "reset":
            id0 = self._process_bit_id(node.children[0])
            for i, _ in enumerate(id0):
                self.dag.apply_operation_back(Reset(), [id0[i]], [], self.condition)

        elif node.type == "if":
            self._process_if(node)

        elif node.type == "opaque":
            self._process_gate(node, opaque=True)

        elif node.type == "external":
            raise QiskitError("internal error: _process_node on external")

        else:
            raise QiskitError("internal error: undefined node type",
                              node.type, "line=%s" % node.line,
                              "file=%s" % node.file)
        return None

Response: Carry out the action associated with a node.


Instruction:
Write a Python 3 function that can
create a DAG node out of a parsed AST op node.

Response:
def _create_dag_op(self, name, params, qargs):
        """
        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
        """
        if name == "u0":
            op_class = U0Gate
        elif name == "u1":
            op_class = U1Gate
        elif name == "u2":
            op_class = U2Gate
        elif name == "u3":
            op_class = U3Gate
        elif name == "x":
            op_class = XGate
        elif name == "y":
            op_class = YGate
        elif name == "z":
            op_class = ZGate
        elif name == "t":
            op_class = TGate
        elif name == "tdg":
            op_class = TdgGate
        elif name == "s":
            op_class = SGate
        elif name == "sdg":
            op_class = SdgGate
        elif name == "swap":
            op_class = SwapGate
        elif name == "rx":
            op_class = RXGate
        elif name == "ry":
            op_class = RYGate
        elif name == "rz":
            op_class = RZGate
        elif name == "rzz":
            op_class = RZZGate
        elif name == "id":
            op_class = IdGate
        elif name == "h":
            op_class = HGate
        elif name == "cx":
            op_class = CnotGate
        elif name == "cy":
            op_class = CyGate
        elif name == "cz":
            op_class = CzGate
        elif name == "ch":
            op_class = CHGate
        elif name == "crz":
            op_class = CrzGate
        elif name == "cu1":
            op_class = Cu1Gate
        elif name == "cu3":
            op_class = Cu3Gate
        elif name == "ccx":
            op_class = ToffoliGate
        elif name == "cswap":
            op_class = FredkinGate
        else:
            raise QiskitError("unknown operation for ast node name %s" % name)

        op = op_class(*params)

        self.dag.apply_operation_back(op, qargs, [], condition=self.condition)


Instruction:
Can you tell what is the following Python 3 function doing
def qasm(self, prec=15):
        return "measure " + self.children[0].qasm(prec) + " -> " + \
               self.children[1].qasm(prec) + ";"

Response: Return the corresponding OPENQASM string.


Instruction:
Write a Python 3 function that can
return the duration of the supplied channels.

Response:
def ch_duration(self, *channels: List[Channel]) -> int:
        """Return duration of supplied channels.

        Args:
            *channels: Supplied channels
        """
        return self.timeslots.ch_duration(*channels)


Instruction:
Given the following Python 3 function, write the documentation
def ch_start_time(self, *channels: List[Channel]) -> int:
        return self.timeslots.ch_start_time(*channels)

Response: Return the minimum start time for the supplied channels.


Instruction:
Can you generate the documentation for the following Python 3 function
def ch_stop_time(self, *channels: List[Channel]) -> int:
        return self.timeslots.ch_stop_time(*channels)

Response: Return the maximum start time for the given channels.


Instruction:
Can you write a function in Python 3 where it
iterates over the Instructions in the schedule tree.

Response:
def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]:
        """Iterable for flattening Schedule tree.

        Args:
            time: Shifted time due to parent

        Yields:
            Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
                at and the flattened `ScheduleComponent`.
        """
        for insert_time, child_sched in self.children:
            yield from child_sched._instructions(time + insert_time)


Instruction:
Write a Python 3 script for
validating a value against the expected type of the a .

Response:
def check_type(self, value, attr, data):
        """Validates a value against the correct type of the field.

        It calls ``_expected_types`` to get a list of valid types.

        Subclasses can do one of the following:

            1. They can override the ``valid_types`` property with a tuple with
            the expected types for this field.

            2. They can override the ``_expected_types`` method to return a
            tuple of expected types for the field.

            3. They can change ``check_type`` completely to customize
            validation.

        This method or the overrides must return the ``value`` parameter
        untouched.
        """
        expected_types = self._expected_types()
        if not isinstance(value, expected_types):
            raise self._not_expected_type(
                value, expected_types, fields=[self], field_names=attr, data=data)
        return value


Instruction:
Implement a function in Python 3 to
dump additional data into a dictionary.

Response:
def dump_additional_data(self, valid_data, many, original_data):
        """Include unknown fields after dumping.

        Unknown fields are added with no processing at all.

        Args:
            valid_data (dict or list): data collected and returned by ``dump()``.
            many (bool): if True, data and original_data are a list.
            original_data (object or list): object passed to ``dump()`` in the
                first place.

        Returns:
            dict: the same ``valid_data`` extended with the unknown attributes.

        Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
        """
        if many:
            for i, _ in enumerate(valid_data):
                additional_keys = set(original_data[i].__dict__) - set(valid_data[i])
                for key in additional_keys:
                    valid_data[i][key] = getattr(original_data[i], key)
        else:
            additional_keys = set(original_data.__dict__) - set(valid_data)
            for key in additional_keys:
                valid_data[key] = getattr(original_data, key)

        return valid_data


Instruction:
Can you create a Python 3 function that
loads additional data from the original data.

Response:
def load_additional_data(self, valid_data, many, original_data):
        """Include unknown fields after load.

        Unknown fields are added with no processing at all.

        Args:
            valid_data (dict or list): validated data returned by ``load()``.
            many (bool): if True, data and original_data are a list.
            original_data (dict or list): data passed to ``load()`` in the
                first place.

        Returns:
            dict: the same ``valid_data`` extended with the unknown attributes.

        Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
        """
        if many:
            for i, _ in enumerate(valid_data):
                additional_keys = set(original_data[i]) - set(valid_data[i])
                for key in additional_keys:
                    valid_data[i][key] = original_data[i][key]
        else:
            additional_keys = set(original_data) - set(valid_data)
            for key in additional_keys:
                valid_data[key] = original_data[key]

        return valid_data


Instruction:
Explain what the following Python 3 code does
def _create_validation_schema(schema_cls):
        validation_schema = schema_cls()
        for _, field in validation_schema.fields.items():
            if isinstance(field, ModelTypeValidator):
                validate_function = field.__class__.check_type
                field._deserialize = MethodType(validate_function, field)

        return validation_schema

Response: Create a patched Schema for validating models.


Instruction:
Can you write a function in Python 3 where it
validates the internal representation of the instance.

Response:
def _validate(instance):
        """Validate the internal representation of the instance."""
        try:
            _ = instance.schema.validate(instance.to_dict())
        except ValidationError as ex:
            raise ModelValidationError(
                ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs)


Instruction:
How would you code a function in Python 3 to
add validation after instantiation.

Response:
def _validate_after_init(init_method):
        """Add validation after instantiation."""

        @wraps(init_method)
        def _decorated(self, **kwargs):
            try:
                _ = self.shallow_schema.validate(kwargs)
            except ValidationError as ex:
                raise ModelValidationError(
                    ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None

            init_method(self, **kwargs)

        return _decorated


Instruction:
Explain what the following Python 3 code does
def to_dict(self):
        try:
            data, _ = self.schema.dump(self)
        except ValidationError as ex:
            raise ModelValidationError(
                ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None

        return data

Response: Serialize the model into a Python dict of simple types.


Instruction:
Explain what the following Python 3 code does
def partial_trace(state, trace_systems, dimensions=None, reverse=True):
    state = np.array(state)  # convert op to density matrix

    if dimensions is None:  # compute dims if not specified
        num_qubits = int(np.log2(len(state)))
        dimensions = [2 for _ in range(num_qubits)]
        if len(state) != 2 ** num_qubits:
            raise Exception("Input is not a multi-qubit state, "
                            "specify input state dims")
    else:
        dimensions = list(dimensions)

    if isinstance(trace_systems, int):
        trace_systems = [trace_systems]
    else:  # reverse sort trace sys
        trace_systems = sorted(trace_systems, reverse=True)

    # trace out subsystems
    if state.ndim == 1:
        # optimized partial trace for input state vector
        return __partial_trace_vec(state, trace_systems, dimensions, reverse)
    # standard partial trace for input density matrix
    return __partial_trace_mat(state, trace_systems, dimensions, reverse)

Response: Partial trace over subsystems of multi - partite matrix.


Instruction:
How would you implement a function in Python 3 that
flattens an operator to a vector in a specified basis.

Response:
def vectorize(density_matrix, method='col'):
    """Flatten an operator to a vector in a specified basis.

    Args:
        density_matrix (ndarray): a density matrix.
        method (str): the method of vectorization. Allowed values are
            - 'col' (default) flattens to column-major vector.
            - 'row' flattens to row-major vector.
            - 'pauli'flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting vector.
    Raises:
        Exception: if input state is not a n-qubit state
    """
    density_matrix = np.array(density_matrix)
    if method == 'col':
        return density_matrix.flatten(order='F')
    elif method == 'row':
        return density_matrix.flatten(order='C')
    elif method in ['pauli', 'pauli_weights']:
        num = int(np.log2(len(density_matrix)))  # number of qubits
        if len(density_matrix) != 2**num:
            raise Exception('Input state must be n-qubit state')
        if method == 'pauli_weights':
            pgroup = pauli_group(num, case='weight')
        else:
            pgroup = pauli_group(num, case='tensor')
        vals = [np.trace(np.dot(p.to_matrix(), density_matrix))
                for p in pgroup]
        return np.array(vals)
    return None


Instruction:
Can you generate the documentation for the following Python 3 function
def choi_to_rauli(choi, order=1):
    if order == 0:
        order = 'weight'
    elif order == 1:
        order = 'tensor'

    # get number of qubits'
    num_qubits = int(np.log2(np.sqrt(len(choi))))
    pgp = pauli_group(num_qubits, case=order)
    rauli = []
    for i in pgp:
        for j in pgp:
            pauliop = np.kron(j.to_matrix().T, i.to_matrix())
            rauli += [np.trace(np.dot(choi, pauliop))]
    return np.array(rauli).reshape(4 ** num_qubits, 4 ** num_qubits)

Response: Convert a Choi - matrix to a Pauli - basis superoperator.


Instruction:
Can you generate the documentation for the following Python 3 function
def chop(array, epsilon=1e-10):
    ret = np.array(array)

    if np.isrealobj(ret):
        ret[abs(ret) < epsilon] = 0.0
    else:
        ret.real[abs(ret.real) < epsilon] = 0.0
        ret.imag[abs(ret.imag) < epsilon] = 0.0
    return ret

Response: Truncates small values of a complex array.


Instruction:
Write a Python 3 script for
constructing the outer product of two vectors.

Response:
def outer(vector1, vector2=None):
    """
    Construct the outer product of two vectors.

    The second vector argument is optional, if absent the projector
    of the first vector will be returned.

    Args:
        vector1 (ndarray): the first vector.
        vector2 (ndarray): the (optional) second vector.

    Returns:
        np.array: The matrix |v1><v2|.

    """
    if vector2 is None:
        vector2 = np.array(vector1).conj()
    else:
        vector2 = np.array(vector2).conj()
    return np.outer(vector1, vector2)


Instruction:
Can you generate the documentation for the following Python 3 function
def random_unitary_matrix(dim, seed=None):
    warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been '
                  'deprecated and will be removed in the future. Instead use '
                  'the function in qiskit.quantum_info.random',
                  DeprecationWarning)
    return random.random_unitary(dim, seed).data

Response: Returns a random unitary matrix.


Instruction:
Can you write a function in Python 3 where it
returns a random density matrix.

Response:
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):
    """Deprecated in 0.8+
    """
    warnings.warn('The random_density_matrix() function in qiskit.tools.qi has been '
                  'deprecated and will be removed in the future. Instead use '
                  'the function in qiskit.quantum_info.random',
                  DeprecationWarning)
    return random.random_density_matrix(length, rank, method, seed)


Instruction:
Write a Python 3 function for
calculating the concurrence. Args: state (np.array): a quantum state (1x4 array) or a density matrix (4x4 array) Returns: float: concurrence. Raises: Exception: if attempted on more than two qubits.

Response:
def concurrence(state):
    """Calculate the concurrence.

    Args:
        state (np.array): a quantum state (1x4 array) or a density matrix (4x4
                          array)
    Returns:
        float: concurrence.
    Raises:
        Exception: if attempted on more than two qubits.
    """
    rho = np.array(state)
    if rho.ndim == 1:
        rho = outer(state)
    if len(state) != 4:
        raise Exception("Concurrence is only defined for more than two qubits")

    YY = np.fliplr(np.diag([-1, 1, 1, -1]))
    A = rho.dot(YY).dot(rho.conj()).dot(YY)
    w = la.eigh(A, eigvals_only=True)
    w = np.sqrt(np.maximum(w, 0))
    return max(0.0, w[-1] - np.sum(w[0:-1]))


Instruction:
How would you explain what the following Python 3 function does
def shannon_entropy(pvec, base=2):
    # pylint: disable=missing-docstring
    if base == 2:
        def logfn(x):
            return - x * np.log2(x)
    elif base == np.e:
        def logfn(x):
            return - x * np.log(x)
    else:
        def logfn(x):
            return -x * np.log(x) / np.log(base)

    h = 0.
    for x in pvec:
        if 0 < x < 1:
            h += logfn(x)
    return h

Response: Compute the Shannon entropy of a probability vector.


Instruction:
Make a summary of the following Python 3 code
def entropy(state):

    rho = np.array(state)
    if rho.ndim == 1:
        return 0
    evals = np.maximum(np.linalg.eigvalsh(state), 0.)
    return shannon_entropy(evals, base=np.e)

Response: Compute the von - Neumann entropy of a quantum state vector.


Instruction:
Write a Python 3 script for
computing the mutual information of a bipartite state.

Response:
def mutual_information(state, d0, d1=None):
    """
    Compute the mutual information of a bipartite state.

    Args:
        state (array_like): a bipartite state-vector or density-matrix.
        d0 (int): dimension of the first subsystem.
        d1 (int or None): dimension of the second subsystem.

    Returns:
        float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).
    """
    if d1 is None:
        d1 = int(len(state) / d0)
    mi = entropy(partial_trace(state, [0], dimensions=[d0, d1]))
    mi += entropy(partial_trace(state, [1], dimensions=[d0, d1]))
    mi -= entropy(state)
    return mi


Instruction:
Implement a function in Python 3 to
compute the entanglement of formation of a bipartite state vector or 2 - qubit density matrix.

Response:
def entanglement_of_formation(state, d0, d1=None):
    """
    Compute the entanglement of formation of quantum state.

    The input quantum state must be either a bipartite state vector, or a
    2-qubit density matrix.

    Args:
        state (array_like): (N) array_like or (4,4) array_like, a
            bipartite quantum state.
        d0 (int): the dimension of the first subsystem.
        d1 (int or None): the dimension of the second subsystem.

    Returns:
        float: The entanglement of formation.
    """
    state = np.array(state)

    if d1 is None:
        d1 = int(len(state) / d0)

    if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2:
        return __eof_qubit(state)
    elif state.ndim == 1:
        # trace out largest dimension
        if d0 < d1:
            tr = [1]
        else:
            tr = [0]
        state = partial_trace(state, tr, dimensions=[d0, d1])
        return entropy(state)
    else:
        print('Input must be a state-vector or 2-qubit density matrix.')
    return None


Instruction:
Create a Python 3 function to
compute the Entanglement of Formation of a 2 - qubit density matrix.

Response:
def __eof_qubit(rho):
    """
    Compute the Entanglement of Formation of a 2-qubit density matrix.

    Args:
        rho ((array_like): (4,4) array_like, input density matrix.

    Returns:
        float: The entanglement of formation.
    """
    c = concurrence(rho)
    c = 0.5 + 0.5 * np.sqrt(1 - c * c)
    return shannon_entropy([c, 1 - c])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],
          name: str = None) -> Schedule:
    """Create a union (and also shift if desired) of all input `Schedule`s.

    Args:
        *schedules: Schedules to take the union of
        name: Name of the new schedule. Defaults to first element of `schedules`
    """
    if name is None and schedules:
        sched = schedules[0]
        if isinstance(sched, (list, tuple)):
            name = sched[1].name
        else:
            name = sched.name
    return Schedule(*schedules, name=name)

Response: Create a union of all input Schedule s.


Instruction:
Can you tell what is the following Python 3 function doing
def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:
    if name is None:
        name = schedule.name

    return Schedule(*schedule.instructions, name=name)

Response: Create a flattened schedule.


Instruction:
Can you write a function in Python 3 where it
returns a schedule shifted by time.

Response:
def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:
    """Return schedule shifted by `time`.

    Args:
        schedule: The schedule to shift
        time: The time to shift by
        name: Name of shifted schedule. Defaults to name of `schedule`
    """
    if name is None:
        name = schedule.name
    return union((time, schedule), name=name)


Instruction:
Can you create a Python 3 function that
returns a new schedule with the child schedule inserted into the parent at the given time.

Response:
def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,
           name: str = None) -> Schedule:
    """Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`.

    Args:
        parent: Schedule to be inserted into
        time: Time to be inserted defined with respect to `parent`
        child: Schedule to insert
        name: Name of the new schedule. Defaults to name of parent
    """
    return union(parent, (time, child), name=name)


Instruction:
Make a summary of the following Python 3 code
def append(parent: ScheduleComponent, child: ScheduleComponent,
           name: str = None) -> Schedule:
    r"""Return a new schedule with by appending `child` to `parent` at
       the last time of the `parent` schedule's channels
       over the intersection of the parent and child schedule's channels.

       $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$

    Args:
        parent: The schedule to be inserted into
        child: The schedule to insert
        name: Name of the new schedule. Defaults to name of parent
    """
    common_channels = set(parent.channels) & set(child.channels)
    insertion_time = parent.ch_stop_time(*common_channels)
    return insert(parent, insertion_time, child, name=name)

Response:
r Returns a new schedule with by appending child to parent at the last time of the parent schedule s channels
       over the intersection of parent and child s channels.


Instruction:
Can you generate the documentation for the following Python 3 function
def u3(self, theta, phi, lam, q):
    return self.append(U3Gate(theta, phi, lam), [q], [])

Response: Apply u3 to q.


Instruction:
Explain what the following Python 3 code does
def status(self):
        return BackendStatus(backend_name=self.name(),
                             backend_version=__version__,
                             operational=True,
                             pending_jobs=0,
                             status_msg='')

Response: Return the status of the backend.


Instruction:
Write a Python 3 script for
starting the progress bar.

Response:
def start(self, iterations):
        """Start the progress bar.

        Parameters:
            iterations (int): Number of iterations.
        """
        self.touched = True
        self.iter = int(iterations)
        self.t_start = time.time()


Instruction:
Create a Python 3 function to
estimate the remaining time left.

Response:
def time_remaining_est(self, completed_iter):
        """Estimate the remaining time left.

        Parameters:
            completed_iter (int): Number of iterations completed.

        Returns:
            est_time: Estimated time remaining.
        """
        if completed_iter:
            t_r_est = (time.time() - self.t_start) / \
                completed_iter*(self.iter-completed_iter)
        else:
            t_r_est = 0
        date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est)
        time_string = "%02d:%02d:%02d:%02d" % \
            (date_time.day - 1, date_time.hour, date_time.minute, date_time.second)

        return time_string


Instruction:
Create a Python 3 function to
run the CommutativeCancellation pass on a DAG.

Response:
def run(self, dag):
        """Run the CommutativeCancellation pass on a dag

        Args:
            dag (DAGCircuit): the DAG to be optimized.

        Returns:
            DAGCircuit: the optimized DAG.

        Raises:
            TranspilerError: when the 1 qubit rotation gates are not found
        """

        q_gate_list = ['cx', 'cy', 'cz', 'h', 'x', 'y', 'z']

        # Gate sets to be cancelled
        cancellation_sets = defaultdict(lambda: [])

        for wire in dag.wires:
            wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1]))
            wire_commutation_set = self.property_set['commutation_set'][wire_name]

            for com_set_idx, com_set in enumerate(wire_commutation_set):
                if com_set[0].type in ['in', 'out']:
                    continue
                for node in com_set:
                    num_qargs = len(node.qargs)
                    if num_qargs == 1 and node.name in q_gate_list:
                        cancellation_sets[(node.name, wire_name, com_set_idx)].append(node)
                    if num_qargs == 1 and node.name in ['u1', 'rz', 't', 's']:
                        cancellation_sets[('z_rotation', wire_name, com_set_idx)].append(node)
                    elif num_qargs == 2 and node.qargs[0] == wire:
                        second_op_name = "{0}[{1}]".format(str(node.qargs[1][0].name),
                                                           str(node.qargs[1][1]))
                        q2_key = (node.name, wire_name, second_op_name,
                                  self.property_set['commutation_set'][(node, second_op_name)])
                        cancellation_sets[q2_key].append(node)

        for cancel_set_key in cancellation_sets:
            set_len = len(cancellation_sets[cancel_set_key])
            if ((set_len) > 1 and cancel_set_key[0] in q_gate_list):
                gates_to_cancel = cancellation_sets[cancel_set_key]
                for c_node in gates_to_cancel[:(set_len // 2) * 2]:
                    dag.remove_op_node(c_node)

            elif((set_len) > 1 and cancel_set_key[0] == 'z_rotation'):
                run = cancellation_sets[cancel_set_key]
                run_qarg = run[0].qargs[0]
                total_angle = 0.0  # lambda
                for current_node in run:
                    if (current_node.condition is not None
                            or len(current_node.qargs) != 1
                            or current_node.qargs[0] != run_qarg):
                        raise TranspilerError("internal error")

                    if current_node.name in ['u1', 'rz']:
                        current_angle = float(current_node.op.params[0])
                    elif current_node.name == 't':
                        current_angle = sympy.pi / 4
                    elif current_node.name == 's':
                        current_angle = sympy.pi / 2

                    # Compose gates
                    total_angle = current_angle + total_angle

                # Replace the data of the first node in the run
                new_op = U1Gate(total_angle)
                new_qarg = (QuantumRegister(1, 'q'), 0)
                new_dag = DAGCircuit()
                new_dag.add_qreg(new_qarg[0])
                new_dag.apply_operation_back(new_op, [new_qarg])
                dag.substitute_node_with_dag(run[0], new_dag)

                # Delete the other nodes in the run
                for current_node in run[1:]:
                    dag.remove_op_node(current_node)

        return dag


Instruction:
Create a Python 3 function to
convert a QuantumArchive object to a list of QuantumCircuits.

Response:
def _experiments_to_circuits(qobj):
    """Return a list of QuantumCircuit object(s) from a qobj

    Args:
        qobj (Qobj): The Qobj object to convert to QuantumCircuits
    Returns:
        list: A list of QuantumCircuit objects from the qobj

    """
    if qobj.experiments:
        circuits = []
        for x in qobj.experiments:
            quantum_registers = [QuantumRegister(i[1], name=i[0])
                                 for i in x.header.qreg_sizes]
            classical_registers = [ClassicalRegister(i[1], name=i[0])
                                   for i in x.header.creg_sizes]
            circuit = QuantumCircuit(*quantum_registers,
                                     *classical_registers,
                                     name=x.header.name)
            qreg_dict = {}
            creg_dict = {}
            for reg in quantum_registers:
                qreg_dict[reg.name] = reg
            for reg in classical_registers:
                creg_dict[reg.name] = reg
            for i in x.instructions:
                instr_method = getattr(circuit, i.name)
                qubits = []
                try:
                    for qubit in i.qubits:
                        qubit_label = x.header.qubit_labels[qubit]
                        qubits.append(
                            qreg_dict[qubit_label[0]][qubit_label[1]])
                except Exception:  # pylint: disable=broad-except
                    pass
                clbits = []
                try:
                    for clbit in i.memory:
                        clbit_label = x.header.clbit_labels[clbit]
                        clbits.append(
                            creg_dict[clbit_label[0]][clbit_label[1]])
                except Exception:  # pylint: disable=broad-except
                    pass
                params = []
                try:
                    params = i.params
                except Exception:  # pylint: disable=broad-except
                    pass
                if i.name in ['snapshot']:
                    instr_method(
                        i.label,
                        snapshot_type=i.snapshot_type,
                        qubits=qubits,
                        params=params)
                elif i.name == 'initialize':
                    instr_method(params, qubits)
                else:
                    instr_method(*params, *qubits, *clbits)
            circuits.append(circuit)
        return circuits
    return None


Instruction:
How would you explain what the following Python 3 function does
def disassemble(qobj):
    run_config = qobj.config.to_dict()
    user_qobj_header = qobj.header.to_dict()
    circuits = _experiments_to_circuits(qobj)

    return circuits, run_config, user_qobj_header

Response: Dissasemble a qobj and return the circuits run_config and user header


Instruction:
Make a summary of the following Python 3 code
def hamming_distance(str1, str2):
    if len(str1) != len(str2):
        raise VisualizationError('Strings not same length.')
    return sum(s1 != s2 for s1, s2 in zip(str1, str2))

Response: Calculate the Hamming distance between two strings.


Instruction:
How would you implement a function in Python 3 that
plots a histogram of data.

Response:
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
                   sort='asc', target_string=None,
                   legend=None, bar_labels=True, title=None):
    """Plot a histogram of data.

    Args:
        data (list or dict): This is either a list of dictionaries or a single
            dict containing the values to represent (ex {'001': 130})
        figsize (tuple): Figure size in inches.
        color (list or str): String or list of strings for histogram bar colors.
        number_to_keep (int): The number of terms to plot and rest
            is made into a single bar called 'rest'.
        sort (string): Could be 'asc', 'desc', or 'hamming'.
        target_string (str): Target string if 'sort' is a distance measure.
        legend(list): A list of strings to use for labels of the data.
            The number of entries must match the length of data (if data is a
            list or 1 if it's a dict)
        bar_labels (bool): Label each bar in histogram with probability value.
        title (str): A string to use for the plot title

    Returns:
        matplotlib.Figure: A figure for the rendered histogram.

    Raises:
        ImportError: Matplotlib not available.
        VisualizationError: When legend is provided and the length doesn't
            match the input data.
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('Must have Matplotlib installed.')
    if sort not in VALID_SORTS:
        raise VisualizationError("Value of sort option, %s, isn't a "
                                 "valid choice. Must be 'asc', "
                                 "'desc', or 'hamming'")
    elif sort in DIST_MEAS.keys() and target_string is None:
        err_msg = 'Must define target_string when using distance measure.'
        raise VisualizationError(err_msg)

    if isinstance(data, dict):
        data = [data]

    if legend and len(legend) != len(data):
        raise VisualizationError("Length of legendL (%s) doesn't match "
                                 "number of input executions: %s" %
                                 (len(legend), len(data)))

    fig, ax = plt.subplots(figsize=figsize)
    labels = list(sorted(
        functools.reduce(lambda x, y: x.union(y.keys()), data, set())))
    if number_to_keep is not None:
        labels.append('rest')

    if sort in DIST_MEAS.keys():
        dist = []
        for item in labels:
            dist.append(DIST_MEAS[sort](item, target_string))

        labels = [list(x) for x in zip(*sorted(zip(dist, labels),
                                               key=lambda pair: pair[0]))][1]

    labels_dict = OrderedDict()

    # Set bar colors
    if color is None:
        color = ['#648fff', '#dc267f', '#785ef0', '#ffb000', '#fe6100']
    elif isinstance(color, str):
        color = [color]

    all_pvalues = []
    length = len(data)
    for item, execution in enumerate(data):
        if number_to_keep is not None:
            data_temp = dict(Counter(execution).most_common(number_to_keep))
            data_temp["rest"] = sum(execution.values()) - sum(data_temp.values())
            execution = data_temp
        values = []
        for key in labels:
            if key not in execution:
                if number_to_keep is None:
                    labels_dict[key] = 1
                    values.append(0)
                else:
                    values.append(-1)
            else:
                labels_dict[key] = 1
                values.append(execution[key])
        values = np.array(values, dtype=float)
        where_idx = np.where(values >= 0)[0]
        pvalues = values[where_idx] / sum(values[where_idx])
        for value in pvalues:
            all_pvalues.append(value)
        numelem = len(values[where_idx])
        ind = np.arange(numelem)  # the x locations for the groups
        width = 1/(len(data)+1)  # the width of the bars
        rects = []
        for idx, val in enumerate(pvalues):
            label = None
            if not idx and legend:
                label = legend[item]
            if val >= 0:
                rects.append(ax.bar(idx+item*width, val, width, label=label,
                                    color=color[item % len(color)],
                                    zorder=2))
        bar_center = (width / 2) * (length - 1)
        ax.set_xticks(ind + bar_center)
        ax.set_xticklabels(labels_dict.keys(), fontsize=14, rotation=70)
        # attach some text labels
        if bar_labels:
            for rect in rects:
                for rec in rect:
                    height = rec.get_height()
                    if height >= 1e-3:
                        ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height,
                                '%.3f' % float(height),
                                ha='center', va='bottom', zorder=3)
                    else:
                        ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height,
                                '0',
                                ha='center', va='bottom', zorder=3)

    # add some text for labels, title, and axes ticks
    ax.set_ylabel('Probabilities', fontsize=14)
    ax.set_ylim([0., min([1.2, max([1.2 * val for val in all_pvalues])])])
    if sort == 'desc':
        ax.invert_xaxis()

    ax.yaxis.set_major_locator(MaxNLocator(5))
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(14)
    ax.set_facecolor('#eeeeee')
    plt.grid(which='major', axis='y', zorder=0, linestyle='--')
    if title:
        plt.title(title)

    if legend:
        ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.0), ncol=1,
                  borderaxespad=0, frameon=True, fontsize=12)
    if fig:
        plt.close(fig)
    return fig


Instruction:
Create a Python 3 function to
return quaternion for rotation about given axis.

Response:
def quaternion_from_axis_rotation(angle, axis):
    """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.
    """
    out = np.zeros(4, dtype=float)
    if axis == 'x':
        out[1] = 1
    elif axis == 'y':
        out[2] = 1
    elif axis == 'z':
        out[3] = 1
    else:
        raise ValueError('Invalid axis input.')
    out *= math.sin(angle/2.0)
    out[0] = math.cos(angle/2.0)
    return Quaternion(out)


Instruction:
Write a Python 3 function for
generating a quaternion from a set of Euler angles.

Response:
def quaternion_from_euler(angles, order='yzy'):
    """Generate a quaternion from a set of Euler angles.

    Args:
        angles (array_like): Array of Euler angles.
        order (str): Order of Euler rotations.  'yzy' is default.

    Returns:
        Quaternion: Quaternion representation of Euler rotation.
    """
    angles = np.asarray(angles, dtype=float)
    quat = quaternion_from_axis_rotation(angles[0], order[0])\
        * (quaternion_from_axis_rotation(angles[1], order[1])
           * quaternion_from_axis_rotation(angles[2], order[2]))
    quat.normalize(inplace=True)
    return quat


Instruction:
Implement a function in Python 3 to
normalize a Quaternion to unit length so that it represents a valid rotation.

Response:
def normalize(self, inplace=False):
        """Normalizes a Quaternion to unit length
        so that it represents a valid rotation.

        Args:
            inplace (bool): Do an inplace normalization.

        Returns:
            Quaternion: Normalized quaternion.
        """
        if inplace:
            nrm = self.norm()
            self.data /= nrm
            return None
        nrm = self.norm()
        data_copy = np.array(self.data, copy=True)
        data_copy /= nrm
        return Quaternion(data_copy)


Instruction:
Create a Python 3 function for
converting a unit - length quaternion to a rotation matrix.

Response:
def to_matrix(self):
        """Converts a unit-length quaternion to a rotation matrix.

        Returns:
            ndarray: Rotation matrix.
        """
        w, x, y, z = self.normalize().data  # pylint: disable=C0103
        mat = np.array([
            [1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w],
            [2*x*y+2*z*w, 1-2*x**2-2*z**2, 2*y*z-2*x*w],
            [2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x**2-2*y**2]
        ], dtype=float)
        return mat


Instruction:
Explain what the following Python 3 code does
def to_zyz(self):
        mat = self.to_matrix()
        euler = np.zeros(3, dtype=float)
        if mat[2, 2] < 1:
            if mat[2, 2] > -1:
                euler[0] = math.atan2(mat[1, 2], mat[0, 2])
                euler[1] = math.acos(mat[2, 2])
                euler[2] = math.atan2(mat[2, 1], -mat[2, 0])
            else:
                euler[0] = -math.atan2(mat[1, 0], mat[1, 1])
                euler[1] = np.pi
        else:
            euler[0] = math.atan2(mat[1, 0], mat[1, 1])
        return euler

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


Instruction:
How would you implement a function in Python 3 that
processes received data for representation.

Response:
def process_data(data, number_to_keep):
    """ 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.
    """

    result = dict()

    if number_to_keep != 0:
        data_temp = dict(Counter(data).most_common(number_to_keep))
        data_temp['rest'] = sum(data.values()) - sum(data_temp.values())
        data = data_temp

    labels = data
    values = np.array([data[key] for key in labels], dtype=float)
    pvalues = values / sum(values)
    for position, label in enumerate(labels):
        result[label] = round(pvalues[position], 5)

    return result


Instruction:
Create a Python 3 function to
create a histogram representation of the input data.

Response:
def iplot_histogram(data, figsize=None, number_to_keep=None,
                    sort='asc', legend=None):
    """ 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.
    """

    # HTML
    html_template = Template("""
    <p>
        <div id="histogram_$divNumber"></div>
    </p>
    """)

    # JavaScript
    javascript_template = Template("""
    <script>
        requirejs.config({
            paths: {
                qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
            }
        });

        require(["qVisualization"], function(qVisualizations) {
            qVisualizations.plotState("histogram_$divNumber",
                                      "histogram",
                                      $executions,
                                      $options);
        });
    </script>
    """)

    # Process data and execute
    div_number = str(time.time())
    div_number = re.sub('[.]', '', div_number)

    # set default figure size if none provided
    if figsize is None:
        figsize = (7, 5)

    options = {'number_to_keep': 0 if number_to_keep is None else number_to_keep,
               'sort': sort,
               'show_legend': 0,
               'width': int(figsize[0]),
               'height': int(figsize[1])}
    if legend:
        options['show_legend'] = 1

    data_to_plot = []
    if isinstance(data, dict):
        data = [data]

    if legend and len(legend) != len(data):
        raise VisualizationError("Length of legendL (%s) doesn't match number "
                                 "of input executions: %s" %
                                 (len(legend), len(data)))

    for item, execution in enumerate(data):
        exec_data = process_data(execution, options['number_to_keep'])
        out_dict = {'data': exec_data}
        if legend:
            out_dict['name'] = legend[item]
        data_to_plot.append(out_dict)

    html = html_template.substitute({
        'divNumber': div_number
    })

    javascript = javascript_template.substitute({
        'divNumber': div_number,
        'executions': data_to_plot,
        'options': options
    })

    display(HTML(html + javascript))


Instruction:
Can you write a function in Python 3 where it
customizes check_type for handling containers.

Response:
def check_type(self, value, attr, data):
        """Customize check_type for handling containers."""
        # Check the type in the standard way first, in order to fail quickly
        # in case of invalid values.
        root_value = super(InstructionParameter, self).check_type(
            value, attr, data)

        if is_collection(value):
            _ = [super(InstructionParameter, self).check_type(item, attr, data)
                 for item in value]

        return root_value


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_range(self, j):
        if isinstance(j, int):
            if j < 0 or j >= self.size:
                raise QiskitIndexError("register index out of range")
            elif isinstance(j, slice):
                if j.start < 0 or j.stop >= self.size or (j.step is not None and
                                                          j.step <= 0):
                    raise QiskitIndexError("register index slice out of range")

Response: Check that j is a valid index into self.


Instruction:
Write a Python 3 script for
testing if an array is a square matrix.

Response:
def is_square_matrix(mat):
    """Test if an array is a square matrix."""
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    shape = mat.shape
    return shape[0] == shape[1]


Instruction:
Write a Python 3 function for
testing if an array is a diagonal matrix

Response:
def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a diagonal matrix"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol)


Instruction:
Write a Python 3 function for
testing if an array is a symmetrix matrix

Response:
def is_symmetric_matrix(op, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a symmetrix matrix"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(op)
    if mat.ndim != 2:
        return False
    return np.allclose(mat, mat.T, rtol=rtol, atol=atol)


Instruction:
Given the following Python 3 function, write the documentation
def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol)

Response: Test if an array is a Hermitian matrix


Instruction:
Write a Python 3 function for
testing if a matrix is positive semidefinite

Response:
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if a matrix is positive semidefinite"""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
        return False
    # Check eigenvalues are all positive
    vals = np.linalg.eigvalsh(mat)
    for v in vals:
        if v < -atol:
            return False
    return True


Instruction:
Write a Python 3 script to
test if an array is an identity matrix.

Response:
def is_identity_matrix(mat,
                       ignore_phase=False,
                       rtol=RTOL_DEFAULT,
                       atol=ATOL_DEFAULT):
    """Test if an array is an identity matrix."""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    if mat.ndim != 2:
        return False
    if ignore_phase:
        # If the matrix is equal to an identity up to a phase, we can
        # remove the phase by multiplying each entry by the complex
        # conjugate of the phase of the [0, 0] entry.
        theta = np.angle(mat[0, 0])
        mat = np.exp(-1j * theta) * mat
    # Check if square identity
    iden = np.eye(len(mat))
    return np.allclose(mat, iden, rtol=rtol, atol=atol)


Instruction:
How would you code a function in Python 3 to
test if an array is a unitary matrix.

Response:
def is_unitary_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
    """Test if an array is a unitary matrix."""
    if atol is None:
        atol = ATOL_DEFAULT
    if rtol is None:
        rtol = RTOL_DEFAULT
    mat = np.array(mat)
    # Compute A^dagger.A and see if it is identity matrix
    mat = np.conj(mat.T).dot(mat)
    return is_identity_matrix(mat, ignore_phase=False, rtol=rtol, atol=atol)


Instruction:
Given the following Python 3 function, write the documentation
def run(self, dag):
        swaps = dag.op_nodes(SwapGate)
        for swap in swaps:
            final_successor = []
            for successor in dag.successors(swap):
                final_successor.append(successor.type == 'out' or (successor.type == 'op' and
                                                                   successor.op.name == 'measure'))
            if all(final_successor):
                # the node swap needs to be removed and, if a measure follows, needs to be adapted
                swap_qargs = swap.qargs
                measure_layer = DAGCircuit()
                for qreg in dag.qregs.values():
                    measure_layer.add_qreg(qreg)
                for creg in dag.cregs.values():
                    measure_layer.add_creg(creg)
                for successor in dag.successors(swap):
                    if successor.type == 'op' and successor.op.name == 'measure':
                        # replace measure node with a new one, where qargs is set with the "other"
                        # swap qarg.
                        dag.remove_op_node(successor)
                        old_measure_qarg = successor.qargs[0]
                        new_measure_qarg = swap_qargs[swap_qargs.index(old_measure_qarg) - 1]
                        measure_layer.apply_operation_back(Measure(), [new_measure_qarg],
                                                           [successor.cargs[0]])
                dag.extend_back(measure_layer)
                dag.remove_op_node(swap)
        return dag

Response: Return a new circuit that has been optimized.


Instruction:
How would you explain what the following Python 3 function does
def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:
    times = np.arange(duration)
    return continuous_pulse(times, *args, **kwargs)

Response: Left sample a continuous function.


Instruction:
Write a Python 3 function for
transforming a QuantumChannel to the Choi representation.

Response:
def _to_choi(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Choi representation."""
    if rep == 'Choi':
        return data
    if rep == 'Operator':
        return _from_operator('Choi', data, input_dim, output_dim)
    if rep == 'SuperOp':
        return _superop_to_choi(data, input_dim, output_dim)
    if rep == 'Kraus':
        return _kraus_to_choi(data, input_dim, output_dim)
    if rep == 'Chi':
        return _chi_to_choi(data, input_dim, output_dim)
    if rep == 'PTM':
        data = _ptm_to_superop(data, input_dim, output_dim)
        return _superop_to_choi(data, input_dim, output_dim)
    if rep == 'Stinespring':
        return _stinespring_to_choi(data, input_dim, output_dim)
    raise QiskitError('Invalid QuantumChannel {}'.format(rep))


Instruction:
Write a Python 3 script to
transform a QuantumChannel to the SuperOp representation.

Response:
def _to_superop(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the SuperOp representation."""
    if rep == 'SuperOp':
        return data
    if rep == 'Operator':
        return _from_operator('SuperOp', data, input_dim, output_dim)
    if rep == 'Choi':
        return _choi_to_superop(data, input_dim, output_dim)
    if rep == 'Kraus':
        return _kraus_to_superop(data, input_dim, output_dim)
    if rep == 'Chi':
        data = _chi_to_choi(data, input_dim, output_dim)
        return _choi_to_superop(data, input_dim, output_dim)
    if rep == 'PTM':
        return _ptm_to_superop(data, input_dim, output_dim)
    if rep == 'Stinespring':
        return _stinespring_to_superop(data, input_dim, output_dim)
    raise QiskitError('Invalid QuantumChannel {}'.format(rep))


Instruction:
Can you generate the documentation for the following Python 3 function
def _to_kraus(rep, data, input_dim, output_dim):
    if rep == 'Kraus':
        return data
    if rep == 'Stinespring':
        return _stinespring_to_kraus(data, input_dim, output_dim)
    if rep == 'Operator':
        return _from_operator('Kraus', data, input_dim, output_dim)
    # Convert via Choi and Kraus
    if rep != 'Choi':
        data = _to_choi(rep, data, input_dim, output_dim)
    return _choi_to_kraus(data, input_dim, output_dim)

Response: Transform a QuantumChannel to the Kraus representation.


Instruction:
Here you have a function in Python 3, explain what it does
def _to_chi(rep, data, input_dim, output_dim):
    if rep == 'Chi':
        return data
    # Check valid n-qubit input
    _check_nqubit_dim(input_dim, output_dim)
    if rep == 'Operator':
        return _from_operator('Chi', data, input_dim, output_dim)
    # Convert via Choi representation
    if rep != 'Choi':
        data = _to_choi(rep, data, input_dim, output_dim)
    return _choi_to_chi(data, input_dim, output_dim)

Response: Transform a QuantumChannel to the Chi representation.


Instruction:
Can you write a function in Python 3 where it
transforms a QuantumChannel to the PTM representation.

Response:
def _to_ptm(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the PTM representation."""
    if rep == 'PTM':
        return data
    # Check valid n-qubit input
    _check_nqubit_dim(input_dim, output_dim)
    if rep == 'Operator':
        return _from_operator('PTM', data, input_dim, output_dim)
    # Convert via Superoperator representation
    if rep != 'SuperOp':
        data = _to_superop(rep, data, input_dim, output_dim)
    return _superop_to_ptm(data, input_dim, output_dim)


Instruction:
Write a Python 3 script for
transforming a QuantumChannel to the Stinespring representation.

Response:
def _to_stinespring(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Stinespring representation."""
    if rep == 'Stinespring':
        return data
    if rep == 'Operator':
        return _from_operator('Stinespring', data, input_dim, output_dim)
    # Convert via Superoperator representation
    if rep != 'Kraus':
        data = _to_kraus(rep, data, input_dim, output_dim)
    return _kraus_to_stinespring(data, input_dim, output_dim)


Instruction:
Implement a Python 3 function for
transforming a QuantumChannel to the Operator representation.

Response:
def _to_operator(rep, data, input_dim, output_dim):
    """Transform a QuantumChannel to the Operator representation."""
    if rep == 'Operator':
        return data
    if rep == 'Stinespring':
        return _stinespring_to_operator(data, input_dim, output_dim)
    # Convert via Kraus representation
    if rep != 'Kraus':
        data = _to_kraus(rep, data, input_dim, output_dim)
    return _kraus_to_operator(data, input_dim, output_dim)


Instruction:
Write a Python 3 function that can
transform Operator representation to other representation.

Response:
def _from_operator(rep, data, input_dim, output_dim):
    """Transform Operator representation to other representation."""
    if rep == 'Operator':
        return data
    if rep == 'SuperOp':
        return np.kron(np.conj(data), data)
    if rep == 'Choi':
        vec = np.ravel(data, order='F')
        return np.outer(vec, np.conj(vec))
    if rep == 'Kraus':
        return ([data], None)
    if rep == 'Stinespring':
        return (data, None)
    if rep == 'Chi':
        _check_nqubit_dim(input_dim, output_dim)
        data = _from_operator('Choi', data, input_dim, output_dim)
        return _choi_to_chi(data, input_dim, output_dim)
    if rep == 'PTM':
        _check_nqubit_dim(input_dim, output_dim)
        data = _from_operator('SuperOp', data, input_dim, output_dim)
        return _superop_to_ptm(data, input_dim, output_dim)
    raise QiskitError('Invalid QuantumChannel {}'.format(rep))


Instruction:
Make a summary of the following Python 3 code
def _stinespring_to_operator(data, input_dim, output_dim):
    trace_dim = data[0].shape[0] // output_dim
    if data[1] is not None or trace_dim != 1:
        raise QiskitError(
            'Channel cannot be converted to Operator representation')
    return data[0]

Response: Transform Stinespring representation to Operator representation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _superop_to_choi(data, input_dim, output_dim):
    shape = (output_dim, output_dim, input_dim, input_dim)
    return _reshuffle(data, shape)

Response: Transform SuperOp representation to Choi representation.


Instruction:
Can you create a Python 3 function that
transforms Choi to SuperOp representation.

Response:
def _choi_to_superop(data, input_dim, output_dim):
    """Transform Choi to SuperOp representation."""
    shape = (input_dim, output_dim, input_dim, output_dim)
    return _reshuffle(data, shape)


Instruction:
Create a Python 3 function for
transforming Kraus representation to Choi representation.

Response:
def _kraus_to_choi(data, input_dim, output_dim):
    """Transform Kraus representation to Choi representation."""
    choi = 0
    kraus_l, kraus_r = data
    if kraus_r is None:
        for i in kraus_l:
            vec = i.ravel(order='F')
            choi += np.outer(vec, vec.conj())
    else:
        for i, j in zip(kraus_l, kraus_r):
            choi += np.outer(i.ravel(order='F'), j.ravel(order='F').conj())
    return choi


Instruction:
Make a summary of the following Python 3 code
def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):
    # Check if hermitian matrix
    if is_hermitian_matrix(data, atol=atol):
        # Get eigen-decomposition of Choi-matrix
        w, v = la.eigh(data)
        # Check eigenvaleus are non-negative
        if len(w[w < -atol]) == 0:
            # CP-map Kraus representation
            kraus = []
            for val, vec in zip(w, v.T):
                if abs(val) > atol:
                    k = np.sqrt(val) * vec.reshape(
                        (output_dim, input_dim), order='F')
                    kraus.append(k)
            # If we are converting a zero matrix, we need to return a Kraus set
            # with a single zero-element Kraus matrix
            if not kraus:
                kraus.append(np.zeros((output_dim, input_dim), dtype=complex))
            return (kraus, None)
    # Non-CP-map generalized Kraus representation
    mat_u, svals, mat_vh = la.svd(data)
    kraus_l = []
    kraus_r = []
    for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()):
        kraus_l.append(
            np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='F'))
        kraus_r.append(
            np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='F'))
    return (kraus_l, kraus_r)

Response: Transform Choi representation to Kraus representation.


Instruction:
Create a Python 3 function to
transform Stinespring representation to Kraus representation.

Response:
def _stinespring_to_kraus(data, input_dim, output_dim):
    """Transform Stinespring representation to Kraus representation."""
    kraus_pair = []
    for stine in data:
        if stine is None:
            kraus_pair.append(None)
        else:
            trace_dim = stine.shape[0] // output_dim
            iden = np.eye(output_dim)
            kraus = []
            for j in range(trace_dim):
                vec = np.zeros(trace_dim)
                vec[j] = 1
                kraus.append(np.kron(iden, vec[None, :]).dot(stine))
            kraus_pair.append(kraus)
    return tuple(kraus_pair)


Instruction:
How would you explain what the following Python 3 function does
def _stinespring_to_choi(data, input_dim, output_dim):
    trace_dim = data[0].shape[0] // output_dim
    stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
    if data[1] is None:
        stine_r = stine_l
    else:
        stine_r = np.reshape(data[1], (output_dim, trace_dim, input_dim))
    return np.reshape(
        np.einsum('iAj,kAl->jilk', stine_l, stine_r.conj()),
        2 * [input_dim * output_dim])

Response: Transform Stinespring representation to Choi representation.


Instruction:
Can you generate the documentation for the following Python 3 function
def _kraus_to_stinespring(data, input_dim, output_dim):
    stine_pair = [None, None]
    for i, kraus in enumerate(data):
        if kraus is not None:
            num_kraus = len(kraus)
            stine = np.zeros((output_dim * num_kraus, input_dim),
                             dtype=complex)
            for j, mat in enumerate(kraus):
                vec = np.zeros(num_kraus)
                vec[j] = 1
                stine += np.kron(mat, vec[:, None])
            stine_pair[i] = stine
    return tuple(stine_pair)

Response: Transform Kraus representation to Stinespring representation.


Instruction:
Can you implement a function in Python 3 that
transforms Kraus representation to SuperOp representation.

Response:
def _kraus_to_superop(data, input_dim, output_dim):
    """Transform Kraus representation to SuperOp representation."""
    kraus_l, kraus_r = data
    superop = 0
    if kraus_r is None:
        for i in kraus_l:
            superop += np.kron(np.conj(i), i)
    else:
        for i, j in zip(kraus_l, kraus_r):
            superop += np.kron(np.conj(j), i)
    return superop


Instruction:
Can you tell what is the following Python 3 function doing
def _chi_to_choi(data, input_dim, output_dim):
    num_qubits = int(np.log2(input_dim))
    return _transform_from_pauli(data, num_qubits)

Response: Transform Chi representation to a Choi representation.


Instruction:
Make a summary of the following Python 3 code
def _choi_to_chi(data, input_dim, output_dim):
    num_qubits = int(np.log2(input_dim))
    return _transform_to_pauli(data, num_qubits)

Response: Transform Choi representation to the Chi representation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _bipartite_tensor(mat1, mat2, shape1=None, shape2=None):
    # Convert inputs to numpy arrays
    mat1 = np.array(mat1)
    mat2 = np.array(mat2)

    # Determine bipartite dimensions if not provided
    dim_a0, dim_a1 = mat1.shape
    dim_b0, dim_b1 = mat2.shape
    if shape1 is None:
        sdim_a0 = int(np.sqrt(dim_a0))
        sdim_a1 = int(np.sqrt(dim_a1))
        shape1 = (sdim_a0, sdim_a0, sdim_a1, sdim_a1)
    if shape2 is None:
        sdim_b0 = int(np.sqrt(dim_b0))
        sdim_b1 = int(np.sqrt(dim_b1))
        shape2 = (sdim_b0, sdim_b0, sdim_b1, sdim_b1)
    # Check dimensions
    if len(shape1) != 4 or shape1[0] * shape1[1] != dim_a0 or \
            shape1[2] * shape1[3] != dim_a1:
        raise QiskitError("Invalid shape_a")
    if len(shape2) != 4 or shape2[0] * shape2[1] != dim_b0 or \
            shape2[2] * shape2[3] != dim_b1:
        raise QiskitError("Invalid shape_b")

    return _reravel(mat1, mat2, shape1, shape2)

Response: This function returns a tensor product of two bipartite matrices and reravel indicies.


Instruction:
Can you create a Python 3 function that
transforms pauli data into a single - qubit basis of bipartite matrix represenation.

Response:
def _transform_from_pauli(data, num_qubits):
    """Change of basis of bipartite matrix represenation."""
    # Change basis: sum_{i=0}^3 =|\sigma_i>><i|
    basis_mat = np.array(
        [[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]],
        dtype=complex)
    # Note that we manually renormalized after change of basis
    # to avoid rounding errors from square-roots of 2.
    cob = basis_mat
    for _ in range(num_qubits - 1):
        dim = int(np.sqrt(len(cob)))
        cob = np.reshape(
            np.transpose(
                np.reshape(
                    np.kron(basis_mat, cob), (2, 2, dim, dim, 4, dim * dim)),
                (0, 2, 1, 3, 4, 5)), (4 * dim * dim, 4 * dim * dim))
    return np.dot(np.dot(cob, data), cob.conj().T) / 2**num_qubits


Instruction:
Write a Python 3 function that can
reshuffle the indicies of a bipartite matrix A [ ij ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki ] - > A [ lj ki

Response:
def _reshuffle(mat, shape):
    """Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
    return np.reshape(
        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
        (shape[3] * shape[1], shape[0] * shape[2]))


Instruction:
How would you implement a function in Python 3 that
returns true if dims correspond to an n - qubit channel.

Response:
def _check_nqubit_dim(input_dim, output_dim):
    """Return true if dims correspond to an n-qubit channel."""
    if input_dim != output_dim:
        raise QiskitError(
            'Not an n-qubit channel: input_dim' +
            ' ({}) != output_dim ({})'.format(input_dim, output_dim))
    num_qubits = int(np.log2(input_dim))
    if 2**num_qubits != input_dim:
        raise QiskitError('Not an n-qubit channel: input_dim != 2 ** n')


Instruction:
Can you tell what is the following Python 3 function doing
def _hide_tick_lines_and_labels(axis):
    for item in axis.get_ticklines() + axis.get_ticklabels():
        item.set_visible(False)

Response: Hide ticklines and ticklabels of an axis.


Instruction:
Can you tell what is the following Python 3 function doing
def set_label_convention(self, convention):
        ketex = "$\\left.|%s\\right\\rangle$"
        # \left.| is on purpose, so that every ket has the same size

        if convention == "original":
            self.xlabel = ['$x$', '']
            self.ylabel = ['$y$', '']
            self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
        elif convention == "xyz":
            self.xlabel = ['$x$', '']
            self.ylabel = ['$y$', '']
            self.zlabel = ['$z$', '']
        elif convention == "sx sy sz":
            self.xlabel = ['$s_x$', '']
            self.ylabel = ['$s_y$', '']
            self.zlabel = ['$s_z$', '']
        elif convention == "01":
            self.xlabel = ['', '']
            self.ylabel = ['', '']
            self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
        elif convention == "polarization jones":
            self.xlabel = [ketex % "\\nearrow\\hspace{-1.46}\\swarrow",
                           ketex % "\\nwarrow\\hspace{-1.46}\\searrow"]
            self.ylabel = [ketex % "\\circlearrowleft", ketex %
                           "\\circlearrowright"]
            self.zlabel = [ketex % "\\leftrightarrow", ketex % "\\updownarrow"]
        elif convention == "polarization jones letters":
            self.xlabel = [ketex % "D", ketex % "A"]
            self.ylabel = [ketex % "L", ketex % "R"]
            self.zlabel = [ketex % "H", ketex % "V"]
        elif convention == "polarization stokes":
            self.ylabel = ["$\\nearrow\\hspace{-1.46}\\swarrow$",
                           "$\\nwarrow\\hspace{-1.46}\\searrow$"]
            self.zlabel = ["$\\circlearrowleft$", "$\\circlearrowright$"]
            self.xlabel = ["$\\leftrightarrow$", "$\\updownarrow$"]
        else:
            raise Exception("No such convention.")

Response: Set x y and z labels according to the convention.


Instruction:
Here you have a function in Python 3, explain what it does
def clear(self):
        self.points = []
        self.vectors = []
        self.point_style = []
        self.annotations = []

Response: Resets all Bloch sphere data sets to empty.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_points(self, points, meth='s'):
        if not isinstance(points[0], (list, np.ndarray)):
            points = [[points[0]], [points[1]], [points[2]]]
        points = np.array(points)
        if meth == 's':
            if len(points[0]) == 1:
                pnts = np.array([[points[0][0]],
                                 [points[1][0]], [points[2][0]]])
                pnts = np.append(pnts, points, axis=1)
            else:
                pnts = points
            self.points.append(pnts)
            self.point_style.append('s')
        elif meth == 'l':
            self.points.append(points)
            self.point_style.append('l')
        else:
            self.points.append(points)
            self.point_style.append('m')

Response: Adds a list of data points to the bloch sphere.


Instruction:
Write a Python 3 script to
add a list of vectors to Bloch sphere.

Response:
def add_vectors(self, vectors):
        """Add a list of vectors to Bloch sphere.

        Args:
            vectors (array_like):
                Array with vectors of unit length or smaller.
        """
        if isinstance(vectors[0], (list, np.ndarray)):
            for vec in vectors:
                self.vectors.append(vec)
        else:
            self.vectors.append(vectors)


Instruction:
Create a Python 3 function for
adding a LaTeX annotation to the Bloch sphere.

Response:
def add_annotation(self, state_or_vector, text, **kwargs):
        """Add a text or LaTeX annotation to Bloch sphere,
        parametrized by a qubit state or a vector.

        Args:
            state_or_vector (array_like):
                Position for the annotation.
                Qobj of a qubit or a vector of 3 elements.
            text (str):
                Annotation text.
                You can use LaTeX, but remember to use raw string
                e.g. r"$\\langle x \\rangle$"
                or escape backslashes
                e.g. "$\\\\langle x \\\\rangle$".
            **kwargs:
                Options as for mplot3d.axes3d.text, including:
                fontsize, color, horizontalalignment, verticalalignment.
        Raises:
            Exception: If input not array_like or tuple.
        """
        if isinstance(state_or_vector, (list, np.ndarray, tuple)) \
                and len(state_or_vector) == 3:
            vec = state_or_vector
        else:
            raise Exception("Position needs to be specified by a qubit " +
                            "state or a 3D vector.")
        self.annotations.append({'position': vec,
                                 'text': text,
                                 'opts': kwargs})