Instruction:
Explain what the following Python 3 code does
def render(self, title=''):
        if self._rendered:
            self.axes.clear()

        self._rendered = True

        # Figure instance for Bloch sphere plot
        if not self._ext_fig:
            self.fig = plt.figure(figsize=self.figsize)

        if not self._ext_axes:
            self.axes = Axes3D(self.fig, azim=self.view[0], elev=self.view[1])

        if self.background:
            self.axes.clear()
            self.axes.set_xlim3d(-1.3, 1.3)
            self.axes.set_ylim3d(-1.3, 1.3)
            self.axes.set_zlim3d(-1.3, 1.3)
        else:
            self.plot_axes()
            self.axes.set_axis_off()
            self.axes.set_xlim3d(-0.7, 0.7)
            self.axes.set_ylim3d(-0.7, 0.7)
            self.axes.set_zlim3d(-0.7, 0.7)

        self.axes.grid(False)
        self.plot_back()
        self.plot_points()
        self.plot_vectors()
        self.plot_front()
        self.plot_axes_labels()
        self.plot_annotations()
        self.axes.set_title(title, fontsize=self.font_size, y=1.08)

Response: Render the Bloch sphere and its data sets in on given figure and axes.


Instruction:
How would you implement a function in Python 3 that
plots the front half of the sphere.

Response:
def plot_front(self):
        """front half of sphere"""
        u_angle = np.linspace(-np.pi, 0, 25)
        v_angle = np.linspace(0, np.pi, 25)
        x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))
        y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))
        z_dir = np.outer(np.ones(u_angle.shape[0]), np.cos(v_angle))
        self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=2, cstride=2,
                               color=self.sphere_color, linewidth=0,
                               alpha=self.sphere_alpha)
        # wireframe
        self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=5, cstride=5,
                                 color=self.frame_color,
                                 alpha=self.frame_alpha)
        # equator
        self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
                       zs=0, zdir='z', lw=self.frame_width,
                       color=self.frame_color)
        self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle),
                       zs=0, zdir='x', lw=self.frame_width,
                       color=self.frame_color)


Instruction:
Given the following Python 3 function, write the documentation
def plot_axes(self):
        span = np.linspace(-1.0, 1.0, 2)
        self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X',
                       lw=self.frame_width, color=self.frame_color)
        self.axes.plot(0 * span, span, zs=0, zdir='z', label='Y',
                       lw=self.frame_width, color=self.frame_color)
        self.axes.plot(0 * span, span, zs=0, zdir='y', label='Z',
                       lw=self.frame_width, color=self.frame_color)

Response: Plot the current log entry.


Instruction:
Make a summary of the following Python 3 code
def plot_axes_labels(self):
        opts = {'fontsize': self.font_size,
                'color': self.font_color,
                'horizontalalignment': 'center',
                'verticalalignment': 'center'}
        self.axes.text(0, -self.xlpos[0], 0, self.xlabel[0], **opts)
        self.axes.text(0, -self.xlpos[1], 0, self.xlabel[1], **opts)

        self.axes.text(self.ylpos[0], 0, 0, self.ylabel[0], **opts)
        self.axes.text(self.ylpos[1], 0, 0, self.ylabel[1], **opts)

        self.axes.text(0, 0, self.zlpos[0], self.zlabel[0], **opts)
        self.axes.text(0, 0, self.zlpos[1], self.zlabel[1], **opts)

        for item in (self.axes.w_xaxis.get_ticklines() +
                     self.axes.w_xaxis.get_ticklabels()):
            item.set_visible(False)
        for item in (self.axes.w_yaxis.get_ticklines() +
                     self.axes.w_yaxis.get_ticklabels()):
            item.set_visible(False)
        for item in (self.axes.w_zaxis.get_ticklines() +
                     self.axes.w_zaxis.get_ticklabels()):
            item.set_visible(False)

Response: plot the axes labels


Instruction:
Can you write a function in Python 3 where it
plots the vector of the current object.

Response:
def plot_vectors(self):
        """Plot vector"""
        # -X and Y data are switched for plotting purposes
        for k in range(len(self.vectors)):

            xs3d = self.vectors[k][1] * np.array([0, 1])
            ys3d = -self.vectors[k][0] * np.array([0, 1])
            zs3d = self.vectors[k][2] * np.array([0, 1])

            color = self.vector_color[np.mod(k, len(self.vector_color))]

            if self.vector_style == '':
                # simple line style
                self.axes.plot(xs3d, ys3d, zs3d,
                               zs=0, zdir='z', label='Z',
                               lw=self.vector_width, color=color)
            else:
                # decorated style, with arrow heads
                arr = Arrow3D(xs3d, ys3d, zs3d,
                              mutation_scale=self.vector_mutation,
                              lw=self.vector_width,
                              arrowstyle=self.vector_style,
                              color=color)

                self.axes.add_artist(arr)


Instruction:
Can you generate the documentation for the following Python 3 function
def plot_points(self):
        # -X and Y data are switched for plotting purposes
        for k in range(len(self.points)):
            num = len(self.points[k][0])
            dist = [np.sqrt(self.points[k][0][j] ** 2 +
                            self.points[k][1][j] ** 2 +
                            self.points[k][2][j] ** 2) for j in range(num)]
            if any(abs(dist - dist[0]) / dist[0] > 1e-12):
                # combine arrays so that they can be sorted together
                zipped = list(zip(dist, range(num)))
                zipped.sort()  # sort rates from lowest to highest
                dist, indperm = zip(*zipped)
                indperm = np.array(indperm)
            else:
                indperm = np.arange(num)
            if self.point_style[k] == 's':
                self.axes.scatter(
                    np.real(self.points[k][1][indperm]),
                    - np.real(self.points[k][0][indperm]),
                    np.real(self.points[k][2][indperm]),
                    s=self.point_size[np.mod(k, len(self.point_size))],
                    alpha=1,
                    edgecolor='none',
                    zdir='z',
                    color=self.point_color[np.mod(k, len(self.point_color))],
                    marker=self.point_marker[np.mod(k,
                                                    len(self.point_marker))])

            elif self.point_style[k] == 'm':
                pnt_colors = np.array(self.point_color *
                                      int(np.ceil(num /
                                                  float(len(self.point_color)))))

                pnt_colors = pnt_colors[0:num]
                pnt_colors = list(pnt_colors[indperm])
                marker = self.point_marker[np.mod(k, len(self.point_marker))]
                pnt_size = self.point_size[np.mod(k, len(self.point_size))]
                self.axes.scatter(np.real(self.points[k][1][indperm]),
                                  -np.real(self.points[k][0][indperm]),
                                  np.real(self.points[k][2][indperm]),
                                  s=pnt_size, alpha=1, edgecolor='none',
                                  zdir='z', color=pnt_colors,
                                  marker=marker)

            elif self.point_style[k] == 'l':
                color = self.point_color[np.mod(k, len(self.point_color))]
                self.axes.plot(np.real(self.points[k][1]),
                               -np.real(self.points[k][0]),
                               np.real(self.points[k][2]),
                               alpha=0.75, zdir='z',
                               color=color)

Response: Plot points in the current image.


Instruction:
Can you implement a function in Python 3 that
plots the annotations of the current object.

Response:
def plot_annotations(self):
        """Plot annotations"""
        # -X and Y data are switched for plotting purposes
        for annotation in self.annotations:
            vec = annotation['position']
            opts = {'fontsize': self.font_size,
                    'color': self.font_color,
                    'horizontalalignment': 'center',
                    'verticalalignment': 'center'}
            opts.update(annotation['opts'])
            self.axes.text(vec[1], -vec[0], vec[2],
                           annotation['text'], **opts)


Instruction:
Make a summary of the following Python 3 code
def show(self, title=''):
        self.render(title=title)
        if self.fig:
            plt.show(self.fig)

Response: Display Bloch sphere and corresponding data sets.


Instruction:
Here you have a function in Python 3, explain what it does
def save(self, name=None, output='png', dirc=None):

        self.render()
        if dirc:
            if not os.path.isdir(os.getcwd() + "/" + str(dirc)):
                os.makedirs(os.getcwd() + "/" + str(dirc))
        if name is None:
            if dirc:
                self.fig.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' +
                                 str(self.savenum) + '.' + output)
            else:
                self.fig.savefig(os.getcwd() + '/bloch_' + str(self.savenum) +
                                 '.' + output)
        else:
            self.fig.savefig(name)
        self.savenum += 1
        if self.fig:
            plt.close(self.fig)

Response: Saves the Bloch sphere to file of type format.


Instruction:
How would you explain what the following Python 3 function does
def two_qubit_kak(unitary_matrix, verify_gate_sequence=False):
    warnings.warn("two_qubit_kak function is now accessible under "
                  "qiskit.quantum_info.synthesis", DeprecationWarning)
    return synthesis.two_qubit_kak(unitary_matrix)

Response: Two - qubit Kak synthesis.


Instruction:
Can you tell what is the following Python 3 function doing
def top(self):
        ret = self.top_format % self.top_connect.center(
            self.width, self.top_pad)
        if self.right_fill:
            ret = ret.ljust(self.right_fill, self.top_pad)
        if self.left_fill:
            ret = ret.rjust(self.left_fill, self.top_pad)
        ret = ret.center(self.layer_width, self.top_bck)
        return ret

Response: Construct the top line of the element


Instruction:
Can you implement a function in Python 3 that
constructs the middle line of the element

Response:
def mid(self):
        """ Constructs the middle line of the element"""
        ret = self.mid_format % self.mid_content.center(
            self.width, self._mid_padding)
        if self.right_fill:
            ret = ret.ljust(self.right_fill, self._mid_padding)
        if self.left_fill:
            ret = ret.rjust(self.left_fill, self._mid_padding)
        ret = ret.center(self.layer_width, self.mid_bck)
        return ret


Instruction:
Explain what the following Python 3 code does
def bot(self):
        ret = self.bot_format % self.bot_connect.center(
            self.width, self.bot_pad)
        if self.right_fill:
            ret = ret.ljust(self.right_fill, self.bot_pad)
        if self.left_fill:
            ret = ret.rjust(self.left_fill, self.bot_pad)
        ret = ret.center(self.layer_width, self.bot_bck)
        return ret

Response: Constructs the bottom line of the element


Instruction:
Write a Python 3 script to
return the length of the element including the box around.

Response:
def length(self):
        """ Returns the length of the element, including the box around."""
        return max(len(self.top), len(self.mid), len(self.bot))


Instruction:
Given the following Python 3 function, write the documentation
def connect(self, wire_char, where, label=None):

        if 'top' in where and self.top_connector:
            self.top_connect = self.top_connector[wire_char]

        if 'bot' in where and self.bot_connector:
            self.bot_connect = self.bot_connector[wire_char]

        if label:
            self.top_format = self.top_format[:-1] + (label if label else "")

Response: Connect boxes and elements using wire_char and setting proper connectors.


Instruction:
Can you create a Python 3 function that
centers the label vertically.

Response:
def center_label(self, input_length, order):
        """
        In multi-bit elements, the label is centered vertically.
        Args:
            input_length (int): Rhe amount of wires affected.
            order (int): Which middle element is this one?
        """
        location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
        top_limit = order * 2 + 2
        bot_limit = top_limit + 2
        if top_limit <= location_in_the_box < bot_limit:
            if location_in_the_box == top_limit:
                self.top_connect = self.label
            elif location_in_the_box == top_limit + 1:
                self.mid_content = self.label
            else:
                self.bot_connect = self.label


Instruction:
Explain what the following Python 3 code does
def fillup_layer(layer, first_clbit):
        for nones in [i for i, x in enumerate(layer) if x is None]:
            layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
        return layer

Response: Given a layer with Nones replace the Nones in it with EmptyWire elements.


Instruction:
Can you tell what is the following Python 3 function doing
def fillup_layer(layer_length, arrow_char):
        breakwire_layer = []
        for _ in range(layer_length):
            breakwire_layer.append(BreakWire(arrow_char))
        return breakwire_layer

Response: Creates a layer with BreakWire elements.


Instruction:
Can you write a function in Python 3 where it
creates a layer with InputWire elements.

Response:
def fillup_layer(names):  # pylint: disable=arguments-differ
        """
        Creates a layer with InputWire elements.
        Args:
            names (list): List of names for the wires.

        Returns:
            list: The new layer
        """
        longest = max([len(name) for name in names])
        inputs_wires = []
        for name in names:
            inputs_wires.append(InputWire(name.rjust(longest)))
        return inputs_wires


Instruction:
Write a Python 3 script for
dumping the ascii art in the file.

Response:
def dump(self, filename, encoding="utf8"):
        """
        Dumps the ascii art in the file.
        Args:
            filename (str): File to dump the ascii art.
            encoding (str): Optional. Default "utf-8".
        """
        with open(filename, mode='w', encoding=encoding) as text_file:
            text_file.write(self.single_string())


Instruction:
Explain what the following Python 3 code does
def lines(self, line_length=None):
        if line_length is None:
            line_length = self.line_length
        if line_length is None:
            if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
                line_length = 80
            else:
                line_length, _ = get_terminal_size()

        noqubits = len(self.qregs)

        layers = self.build_layers()

        if not line_length:
            line_length = self.line_length

        layer_groups = [[]]
        rest_of_the_line = line_length
        for layerno, layer in enumerate(layers):
            # Replace the Nones with EmptyWire
            layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)

            TextDrawing.normalize_width(layer)

            if line_length == -1:
                # Do not use pagination (aka line breaking. aka ignore line_length).
                layer_groups[-1].append(layer)
                continue

            # chop the layer to the line_length (pager)
            layer_length = layers[layerno][0].length

            if layer_length < rest_of_the_line:
                layer_groups[-1].append(layer)
                rest_of_the_line -= layer_length
            else:
                layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))

                # New group
                layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
                rest_of_the_line = line_length - layer_groups[-1][-1][0].length

                layer_groups[-1].append(
                    InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
                rest_of_the_line -= layer_groups[-1][-1][0].length

                layer_groups[-1].append(layer)
                rest_of_the_line -= layer_groups[-1][-1][0].length

        lines = []
        for layer_group in layer_groups:
            wires = [i for i in zip(*layer_group)]
            lines += TextDrawing.draw_wires(wires, self.vertically_compressed)

        return lines

Response: Generates a list of lines for the current language.


Instruction:
Write a Python 3 script for
returning a list of wire names for each wire.

Response:
def wire_names(self, with_initial_value=True):
        """
        Returns a list of names for each wire.
        Args:
            with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
                                       the name.

        Returns:
            List: The list of wire names.
        """
        qubit_labels = self._get_qubit_labels()
        clbit_labels = self._get_clbit_labels()

        if with_initial_value:
            qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
            clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
        else:
            qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
            clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]

        return qubit_labels + clbit_labels


Instruction:
Create a Python 3 function for
giving a list of wires creates a list of lines with the text drawing.

Response:
def draw_wires(wires, vertically_compressed=True):
        """
        Given a list of wires, creates a list of lines with the text drawing.
        Args:
            wires (list): A list of wires with instructions.
            vertically_compressed (bool): Default is `True`. It merges the lines
                                     so the drawing will take less vertical room.
        Returns:
            list: A list of lines with the text drawing.
        """
        lines = []
        bot_line = None
        for wire in wires:
            # TOP
            top_line = ''
            for instruction in wire:
                top_line += instruction.top

            if bot_line is None:
                lines.append(top_line)
            else:
                if vertically_compressed:
                    lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
                else:
                    lines.append(TextDrawing.merge_lines(lines[-1], top_line, icod="bot"))

            # MID
            mid_line = ''
            for instruction in wire:
                mid_line += instruction.mid
            lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))

            # BOT
            bot_line = ''
            for instruction in wire:
                bot_line += instruction.bot
            lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))

        return lines


Instruction:
Can you generate a brief explanation for the following Python 3 code
def params_for_label(instruction):

        if not hasattr(instruction.op, 'params'):
            return None
        if all([isinstance(param, ndarray) for param in instruction.op.params]):
            return None

        ret = []
        for param in instruction.op.params:
            if isinstance(param, (sympy.Number, float)):
                ret.append('%.5g' % param)
            else:
                ret.append('%s' % param)
        return ret

Response: Get the params and format them to add them to a label.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def label_for_box(instruction):
        label = instruction.name.capitalize()
        params = TextDrawing.params_for_label(instruction)
        if params:
            label += "(%s)" % ','.join(params)
        return label

Response: Creates the label for a box.


Instruction:
Can you tell what is the following Python 3 function doing
def merge_lines(top, bot, icod="top"):
        ret = ""
        for topc, botc in zip(top, bot):
            if topc == botc:
                ret += topc
            elif topc in '┼╪' and botc == " ":
                ret += "│"
            elif topc == " ":
                ret += botc
            elif topc in '┬╥' and botc in " ║│" and icod == "top":
                ret += topc
            elif topc in '┬' and botc == " " and icod == "bot":
                ret += '│'
            elif topc in '╥' and botc == " " and icod == "bot":
                ret += '║'
            elif topc in '┬│' and botc == "═":
                ret += '╪'
            elif topc in '┬│' and botc == "─":
                ret += '┼'
            elif topc in '└┘║│░' and botc == " " and icod == "top":
                ret += topc
            elif topc in '─═' and botc == " " and icod == "top":
                ret += topc
            elif topc in '─═' and botc == " " and icod == "bot":
                ret += botc
            elif topc in "║╥" and botc in "═":
                ret += "╬"
            elif topc in "║╥" and botc in "─":
                ret += "╫"
            elif topc in '╫╬' and botc in " ":
                ret += "║"
            elif topc == '└' and botc == "┌":
                ret += "├"
            elif topc == '┘' and botc == "┐":
                ret += "┤"
            elif botc in "┐┌" and icod == 'top':
                ret += "┬"
            elif topc in "┘└" and botc in "─" and icod == 'top':
                ret += "┴"
            else:
                ret += botc
        return ret

Response: This function merges two lines of a doubt with the same name.


Instruction:
Write a Python 3 function that can
normalize the width of the elements of the specified layer.

Response:
def normalize_width(layer):
        """
        When the elements of the layer have different widths, sets the width to the max elements.
        Args:
            layer (list): A list of elements.
        """
        instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
        longest = max([instruction.length for instruction in instructions])
        for instruction in instructions:
            instruction.layer_width = longest


Instruction:
Can you generate the documentation for the following Python 3 function
def _instruction_to_gate(self, instruction, layer):

        current_cons = []
        connection_label = None

        # add in a gate that operates over multiple qubits
        def add_connected_gate(instruction, gates, layer, current_cons):
            for i, gate in enumerate(gates):
                layer.set_qubit(instruction.qargs[i], gate)
                actual_index = self.qregs.index(instruction.qargs[i])
                current_cons.append((actual_index, gate))

        if instruction.name == 'measure':
            gate = MeasureFrom()
            layer.set_qubit(instruction.qargs[0], gate)
            layer.set_clbit(instruction.cargs[0], MeasureTo())

        elif instruction.name in ['barrier', 'snapshot', 'save', 'load',
                                  'noise']:
            # barrier
            if not self.plotbarriers:
                return layer, current_cons, connection_label

            for qubit in instruction.qargs:
                layer.set_qubit(qubit, Barrier())

        elif instruction.name == 'swap':
            # swap
            gates = [Ex() for _ in range(len(instruction.qargs))]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'cswap':
            # cswap
            gates = [Bullet(), Ex(), Ex()]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'reset':
            layer.set_qubit(instruction.qargs[0], Reset())

        elif instruction.condition is not None:
            # conditional
            cllabel = TextDrawing.label_for_conditional(instruction)
            qulabel = TextDrawing.label_for_box(instruction)

            layer.set_cl_multibox(instruction.condition[0], cllabel, top_connect='┴')
            layer.set_qubit(instruction.qargs[0], BoxOnQuWire(qulabel, bot_connect='┬'))

        elif instruction.name in ['cx', 'CX', 'ccx']:
            # cx/ccx
            gates = [Bullet() for _ in range(len(instruction.qargs) - 1)]
            gates.append(BoxOnQuWire('X'))
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'cy':
            # cy
            gates = [Bullet(), BoxOnQuWire('Y')]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'cz':
            # cz
            gates = [Bullet(), Bullet()]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'ch':
            # ch
            gates = [Bullet(), BoxOnQuWire('H')]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'cu1':
            # cu1
            connection_label = TextDrawing.params_for_label(instruction)[0]
            gates = [Bullet(), Bullet()]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'rzz':
            # rzz
            connection_label = "zz(%s)" % TextDrawing.params_for_label(instruction)[0]
            gates = [Bullet(), Bullet()]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'cu3':
            # cu3
            params = TextDrawing.params_for_label(instruction)
            gates = [Bullet(), BoxOnQuWire("U3(%s)" % ','.join(params))]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif instruction.name == 'crz':
            # crz
            label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]

            gates = [Bullet(), BoxOnQuWire(label)]
            add_connected_gate(instruction, gates, layer, current_cons)

        elif len(instruction.qargs) == 1 and not instruction.cargs:
            # unitary gate
            layer.set_qubit(instruction.qargs[0],
                            BoxOnQuWire(TextDrawing.label_for_box(instruction)))

        elif len(instruction.qargs) >= 2 and not instruction.cargs:
            # multiple qubit gate
            label = instruction.name
            params = TextDrawing.params_for_label(instruction)
            if params:
                label += "(%s)" % ','.join(params)
            layer.set_qu_multibox(instruction.qargs, label)

        else:
            raise VisualizationError(
                "Text visualizer does not know how to handle this instruction", instruction)

        # sort into the order they were declared in
        # this ensures that connected boxes have lines in the right direction
        current_cons.sort(key=lambda tup: tup[0])
        current_cons = [g for q, g in current_cons]

        return layer, current_cons, connection_label

Response:
Convert an instruction into a corresponding Gate object and establish
            any connections it introduces between qubits


Instruction:
Can you generate the documentation for the following Python 3 function
def build_layers(self):
        wire_names = self.wire_names(with_initial_value=True)
        if not wire_names:
            return []

        layers = [InputWire.fillup_layer(wire_names)]

        for instruction_layer in self.instructions:
            layer = Layer(self.qregs, self.cregs)

            for instruction in instruction_layer:
                layer, current_connections, connection_label = \
                    self._instruction_to_gate(instruction, layer)

                layer.connections.append((connection_label, current_connections))
                layer.connect_with("│")
            layers.append(layer.full_layer)

        return layers

Response: Builds the list of layers for the current language.


Instruction:
How would you code a function in Python 3 to
set the qubit to the element in the qubit_layer

Response:
def set_qubit(self, qubit, element):
        """
        Sets the qubit to the element
        Args:
            qubit (qbit): Element of self.qregs.
            element (DrawElement): Element to set in the qubit
        """
        self.qubit_layer[self.qregs.index(qubit)] = element


Instruction:
Can you write a function in Python 3 where it
sets the clbit to the element in the clbit_layer

Response:
def set_clbit(self, clbit, element):
        """
        Sets the clbit to the element
        Args:
            clbit (cbit): Element of self.cregs.
            element (DrawElement): Element to set in the clbit
        """
        self.clbit_layer[self.cregs.index(clbit)] = element


Instruction:
Implement a Python 3 function for
setting the multi - clbit box.

Response:
def set_cl_multibox(self, creg, label, top_connect='┴'):
        """
        Sets the multi clbit box.
        Args:
            creg (string): The affected classical register.
            label (string): The label for the multi clbit box.
            top_connect (char): The char to connect the box on the top.
        """
        clbit = [bit for bit in self.cregs if bit[0] == creg]
        self._set_multibox("cl", clbit, label, top_connect=top_connect)


Instruction:
Make a summary of the following Python 3 code
def connect_with(self, wire_char):

        if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
            # Nothing to connect
            return

        for label, affected_bits in self.connections:

            if not affected_bits:
                continue

            affected_bits[0].connect(wire_char, ['bot'])
            for affected_bit in affected_bits[1:-1]:
                affected_bit.connect(wire_char, ['bot', 'top'])

            affected_bits[-1].connect(wire_char, ['top'], label)

            if label:
                for affected_bit in affected_bits:
                    affected_bit.right_fill = len(label) + len(affected_bit.mid)

Response: Connects the elements in the layer using wire_char.


Instruction:
Explain what the following Python 3 code does
def latex(self, prec=15, nested_scope=None):
        if not nested_scope:
            return "\textrm{" + self.name + "}"
        else:
            if self.name not in nested_scope[-1]:
                raise NodeException("Expected local parameter name: ",
                                    "name=%s, " % self.name,
                                    "line=%s, " % self.line,
                                    "file=%s" % self.file)
            else:
                return nested_scope[-1][self.name].latex(prec,
                                                         nested_scope[0:-1])

Response: Return the correspond math mode latex string.


Instruction:
Can you implement a function in Python 3 that
returns the correspond symbolic number.

Response:
def sym(self, nested_scope=None):
        """Return the correspond symbolic number."""
        if not nested_scope or self.name not in nested_scope[-1]:
            raise NodeException("Expected local parameter name: ",
                                "name=%s, line=%s, file=%s" % (
                                    self.name, self.line, self.file))
        else:
            return nested_scope[-1][self.name].sym(nested_scope[0:-1])


Instruction:
Implement a Python 3 function for
returning the correspond floating point number.

Response:
def real(self, nested_scope=None):
        """Return the correspond floating point number."""
        if not nested_scope or self.name not in nested_scope[-1]:
            raise NodeException("Expected local parameter name: ",
                                "name=%s, line=%s, file=%s" % (
                                    self.name, self.line, self.file))
        else:
            return nested_scope[-1][self.name].real(nested_scope[0:-1])


Instruction:
Can you tell what is the following Python 3 function doing
def compile(circuits, backend,
            config=None, basis_gates=None, coupling_map=None, initial_layout=None,
            shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
            pass_manager=None, memory=False):
    """Compile a list of circuits into a qobj.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (list[str]): list of basis gates names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        seed_mapper (int): random seed for swapper mapper
        qobj_id (int): identifier for the generated qobj
        pass_manager (PassManager): a pass manger for the transpiler pipeline
        memory (bool): if True, per-shot measurement bitstrings are returned as well

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

    Raises:
        QiskitError: if the desired options are not supported by backend
    """
    warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '
                  'Please use qiskit.compiler.transpile() to transform circuits '
                  'and qiskit.compiler.assemble() to produce a runnable qobj.',
                  DeprecationWarning)

    new_circuits = transpile(circuits,
                             basis_gates=basis_gates,
                             coupling_map=coupling_map,
                             initial_layout=initial_layout,
                             seed_transpiler=seed_mapper,
                             backend=backend,
                             pass_manager=pass_manager)

    qobj = assemble(new_circuits,
                    qobj_header=None,
                    shots=shots,
                    max_credits=max_credits,
                    seed_simulator=seed,
                    memory=memory,
                    qobj_id=qobj_id,
                    config=config)  # deprecated

    return qobj

Response: Compile a list of circuits into a single qobj.


Instruction:
Explain what the following Python 3 code does
def _filter_deprecation_warnings():
    deprecation_filter = ('always', None, DeprecationWarning,
                          re.compile(r'^qiskit\.*', re.UNICODE), 0)

    # Instead of using warnings.simple_filter() directly, the internal
    # _add_filter() function is used for being able to match against the
    # module.
    try:
        warnings._add_filter(*deprecation_filter, append=False)
    except AttributeError:
        # ._add_filter is internal and not available in some Python versions.
        pass

    # Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on
    # marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that
    # are useful for eventually migrating, but too verbose for our purposes.
    warnings.simplefilter('ignore', category=ChangedInMarshmallow3Warning)

Response: Apply filters to the deprecation warnings.


Instruction:
Can you write a function in Python 3 where it
checks if internet connection exists to host via specified port.

Response:
def _has_connection(hostname, port):
    """Checks if internet connection exists to host via specified port.

    If any exception is raised while trying to open a socket this will return
    false.

    Args:
        hostname (str): Hostname to connect to.
        port (int): Port to connect to

    Returns:
        bool: Has connection or not

    """
    try:
        host = socket.gethostbyname(hostname)
        socket.create_connection((host, port), 2)
        return True
    except Exception:  # pylint: disable=broad-except
        return False


Instruction:
How would you explain what the following Python 3 function does
def compose(self, other, qargs=None, front=False):
        if qargs is not None:
            return PTM(
                SuperOp(self).compose(other, qargs=qargs, front=front))

        # Convert other to PTM
        if not isinstance(other, PTM):
            other = PTM(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:
            # Composition A(B(input))
            input_dim = other._input_dim
            output_dim = self._output_dim
            return PTM(np.dot(self._data, other.data), input_dim, output_dim)
        # Composition B(A(input))
        input_dim = self._input_dim
        output_dim = other._output_dim
        return PTM(np.dot(other.data, self._data), input_dim, output_dim)

Response: Returns the composition of self and other.


Instruction:
Given the following Python 3 function, write the documentation
def power(self, n):
        if n > 0:
            return super().power(n)
        return PTM(SuperOp(self).power(n))

Response: Returns the matrix power of the superoperator matrix.


Instruction:
Can you generate the documentation for the following Python 3 function
def _html_checker(job_var, interval, status, header,
                  _interval_set=False):
    """Internal function that updates the status
    of a HTML job monitor.

    Args:
        job_var (BaseJob): The job to keep track of.
        interval (int): The status check interval
        status (widget): HTML ipywidget for output ot screen
        header (str): String representing HTML code for status.
        _interval_set (bool): Was interval set by user?
    """
    job_status = job_var.status()
    job_status_name = job_status.name
    job_status_msg = job_status.value
    status.value = header % (job_status_msg)
    while job_status_name not in ['DONE', 'CANCELLED']:
        time.sleep(interval)
        job_status = job_var.status()
        job_status_name = job_status.name
        job_status_msg = job_status.value
        if job_status_name == 'ERROR':
            break
        else:
            if job_status_name == 'QUEUED':
                job_status_msg += ' (%s)' % job_var.queue_position()
                if not _interval_set:
                    interval = max(job_var.queue_position(), 2)
            else:
                if not _interval_set:
                    interval = 2
            status.value = header % (job_status_msg)

    status.value = header % (job_status_msg)

Response: Internal function that updates the status of a HTML job monitor.


Instruction:
Explain what the following Python 3 code does
def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
    x = times/period+phase/np.pi
    return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_)

Response:
Continuous square wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt.
        phase: Pulse phase.


Instruction:
Make a summary of the following Python 3 code
def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
    return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_)

Response:
Continuous triangle wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt.
        phase: Pulse phase.


Instruction:
Can you generate the documentation for the following Python 3 function
def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float,
             zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
             ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
    r"""Continuous unnormalized gaussian pulse.

    Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
            will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
            in which case all samples will be rescaled such that the center
            amplitude will be `amp`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        zeroed_width: Subtract baseline to gaussian pulses to make sure
                 $\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
                 large discontinuities at the start of a gaussian pulse.
        rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
                     be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
        ret_x: Return centered and standard deviation normalized pulse location.
               $x=(times-center)/sigma.
    """
    times = np.asarray(times, dtype=np.complex_)
    x = (times-center)/sigma
    gauss = amp*np.exp(-x**2/2).astype(np.complex_)

    if zeroed_width is not None:
        gauss = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
                                    zeroed_width=zeroed_width, rescale_amp=rescale_amp)

    if ret_x:
        return gauss, x
    return gauss

Response: r Continues unnormalized gaussian pulse.


Instruction:
Explain what the following Python 3 code does
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
                    sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
    r"""Continuous gaussian square pulse.

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude.
        center: Center of the square pulse component.
        width: Width of the square pulse component.
        sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
        zeroed_width: Subtract baseline of gaussian square pulse
                      to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
    """
    square_start = center-width/2
    square_stop = center+width/2
    if zeroed_width:
        zeroed_width = min(width, zeroed_width)
        gauss_zeroed_width = zeroed_width-width
    else:
        gauss_zeroed_width = None

    funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,
                                  zeroed_width=gauss_zeroed_width, rescale_amp=True),
                functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,
                                  zeroed_width=gauss_zeroed_width, rescale_amp=True),
                functools.partial(constant, amp=amp)]
    condlist = [times <= square_start, times >= square_stop]
    return np.piecewise(times.astype(np.complex_), condlist, funclist)

Response: r Continues a gaussian square pulse.


Instruction:
Here you have a function in Python 3, explain what it does
def drag(times: np.ndarray, amp: complex, center: float, sigma: float, beta: float,
         zeroed_width: Union[None, float] = None, rescale_amp: bool = False) -> np.ndarray:
    r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1].

    [1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
        Analytic control methods for high-fidelity unitary operations
        in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
            Where $\lambds_1$ is the relative coupling strength between the first excited and second
            excited states and $\Delta_2$ is the detuning between the resepective excited states.
        zeroed_width: Subtract baseline to gaussian pulses to make sure
                 $\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
                 large discontinuities at the start of a gaussian pulse.
        rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
                     be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.

    """
    gauss_deriv, gauss = gaussian_deriv(times, amp=amp, center=center, sigma=sigma,
                                        ret_gaussian=True)
    if zeroed_width is not None:
        gauss, scale_factor = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,
                                                  zeroed_width=zeroed_width,
                                                  rescale_amp=rescale_amp,
                                                  ret_scale_factor=True)
        gauss_deriv *= scale_factor

    return gauss + 1j*beta*gauss_deriv

Response: Continuous Y - only correction DRAG pulse for a given set of times.


Instruction:
Create a Python 3 function for
returning a pass manager that maps to the coupling map and optimizes it.

Response:
def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
    """
    The default pass manager that maps to the coupling map.

    Args:
        basis_gates (list[str]): list of basis gate names supported by the target.
        coupling_map (CouplingMap): coupling map to target in mapping.
        initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
        seed_transpiler (int or None): random seed for stochastic passes.

    Returns:
        PassManager: A pass manager to map and optimize.
    """
    pass_manager = PassManager()
    pass_manager.property_set['layout'] = initial_layout

    pass_manager.append(Unroller(basis_gates))

    # Use the trivial layout if no layout is found
    pass_manager.append(TrivialLayout(coupling_map),
                        condition=lambda property_set: not property_set['layout'])

    # if the circuit and layout already satisfy the coupling_constraints, use that layout
    # otherwise layout on the most densely connected physical qubit subset
    pass_manager.append(CheckMap(coupling_map))
    pass_manager.append(DenseLayout(coupling_map),
                        condition=lambda property_set: not property_set['is_swap_mapped'])

    # Extend the the dag/layout with ancillas using the full coupling map
    pass_manager.append(FullAncillaAllocation(coupling_map))
    pass_manager.append(EnlargeWithAncilla())

    # Circuit must only contain 1- or 2-qubit interactions for swapper to work
    pass_manager.append(Unroll3qOrMore())

    # Swap mapper
    pass_manager.append(LegacySwap(coupling_map, trials=20, seed=seed_transpiler))

    # Expand swaps
    pass_manager.append(Decompose(SwapGate))

    # Change CX directions
    pass_manager.append(CXDirection(coupling_map))

    # Unroll to the basis
    pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))

    # Simplify single qubit gates and CXs
    simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()]

    pass_manager.append(simplification_passes + [Depth(), FixedPoint('depth')],
                        do_while=lambda property_set: not property_set['depth_fixed_point'])

    return pass_manager


Instruction:
Create a Python 3 function for
returning a default pass manager that just unrolls to basis gates.

Response:
def default_pass_manager_simulator(basis_gates):
    """
    The default pass manager without a coupling map.

    Args:
        basis_gates (list[str]): list of basis gate names to unroll to.

    Returns:
        PassManager: A passmanager that just unrolls, without any optimization.
    """
    pass_manager = PassManager()

    pass_manager.append(Unroller(basis_gates))

    pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')],
                        do_while=lambda property_set: not property_set['depth_fixed_point'])

    return pass_manager


Instruction:
Can you generate a brief explanation for the following Python 3 code
def has_register(self, register):
        has_reg = False
        if (isinstance(register, QuantumRegister) and
                register in self.qregs):
            has_reg = True
        elif (isinstance(register, ClassicalRegister) and
              register in self.cregs):
            has_reg = True
        return has_reg

Response: Test if this circuit has the register r.


Instruction:
Make a summary of the following Python 3 code
def mirror(self):
        reverse_circ = self.copy(name=self.name+'_mirror')
        reverse_circ.data = []
        for inst, qargs, cargs in reversed(self.data):
            reverse_circ.data.append((inst.mirror(), qargs, cargs))
        return reverse_circ

Response: Mirroring the circuit by reversing the instructions.


Instruction:
Given the following Python 3 function, write the documentation
def inverse(self):
        inverse_circ = self.copy(name=self.name+'_dg')
        inverse_circ.data = []
        for inst, qargs, cargs in reversed(self.data):
            inverse_circ.data.append((inst.inverse(), qargs, cargs))
        return inverse_circ

Response: Invert this QuantumCircuit by recursively inverting all gates.


Instruction:
Given the following Python 3 function, write the documentation
def combine(self, rhs):
        # Check registers in LHS are compatible with RHS
        self._check_compatible_regs(rhs)

        # Make new circuit with combined registers
        combined_qregs = deepcopy(self.qregs)
        combined_cregs = deepcopy(self.cregs)

        for element in rhs.qregs:
            if element not in self.qregs:
                combined_qregs.append(element)
        for element in rhs.cregs:
            if element not in self.cregs:
                combined_cregs.append(element)
        circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
        for instruction_context in itertools.chain(self.data, rhs.data):
            circuit.append(*instruction_context)
        return circuit

Response: Combine two QuantumCircuit objects.


Instruction:
Write a Python 3 function for
appending rhs to self.

Response:
def extend(self, rhs):
        """
        Append rhs to self if self contains compatible registers.

        Two circuits are compatible if they contain the same registers
        or if they contain different registers with unique names. The
        returned circuit will contain all unique registers between both
        circuits.

        Modify and return self.
        """
        # Check registers in LHS are compatible with RHS
        self._check_compatible_regs(rhs)

        # Add new registers
        for element in rhs.qregs:
            if element not in self.qregs:
                self.qregs.append(element)
        for element in rhs.cregs:
            if element not in self.cregs:
                self.cregs.append(element)

        # Add new gates
        for instruction_context in rhs.data:
            self.append(*instruction_context)
        return self


Instruction:
How would you explain what the following Python 3 function does
def append(self, instruction, qargs=None, cargs=None):
        qargs = qargs or []
        cargs = cargs or []

        # Convert input to instruction
        if not isinstance(instruction, Instruction) and hasattr(instruction, 'to_instruction'):
            instruction = instruction.to_instruction()
        if not isinstance(instruction, Instruction):
            raise QiskitError('object is not an Instruction.')

        # do some compatibility checks
        self._check_dups(qargs)
        self._check_qargs(qargs)
        self._check_cargs(cargs)
        if instruction.num_qubits != len(qargs) or \
                instruction.num_clbits != len(cargs):
            raise QiskitError("instruction %s with %d qubits and %d clbits "
                              "cannot be appended onto %d qubits and %d clbits." %
                              (instruction.name,
                               instruction.num_qubits, instruction.num_clbits,
                               len(qargs), len(cargs)))

        # add the instruction onto the given wires
        instruction_context = instruction, qargs, cargs
        self.data.append(instruction_context)

        # track variable parameters in instruction
        for param_index, param in enumerate(instruction.params):
            if isinstance(param, Parameter):
                current_symbols = self.parameters

                if param in current_symbols:
                    self._parameter_table[param].append((instruction, param_index))
                else:
                    self._parameter_table[param] = [(instruction, param_index)]

        return instruction

Response: Append an instruction to the end of the circuit modifying the current state of the instruction.


Instruction:
Given the following Python 3 function, write the documentation
def _attach(self, instruction, qargs, cargs):
        self.append(instruction, qargs, cargs)

Response: Deprecated after 0. 8.


Instruction:
Here you have a function in Python 3, explain what it does
def add_register(self, *regs):
        if not regs:
            return

        if any([isinstance(reg, int) for reg in regs]):
            # QuantumCircuit defined without registers
            if len(regs) == 1 and isinstance(regs[0], int):
                # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2)
                regs = (QuantumRegister(regs[0], 'q'),)
            elif len(regs) == 2 and all([isinstance(reg, int) for reg in regs]):
                # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)
                regs = (QuantumRegister(regs[0], 'q'), ClassicalRegister(regs[1], 'c'))
            else:
                raise QiskitError("QuantumCircuit parameters can be Registers or Integers."
                                  " If Integers, up to 2 arguments. QuantumCircuit was called"
                                  " with %s." % (regs,))

        for register in regs:
            if register in self.qregs or register in self.cregs:
                raise QiskitError("register name \"%s\" already exists"
                                  % register.name)
            if isinstance(register, QuantumRegister):
                self.qregs.append(register)
            elif isinstance(register, ClassicalRegister):
                self.cregs.append(register)
            else:
                raise QiskitError("expected a register")

Response: Adds a new register to the list of registers.


Instruction:
Make a summary of the following Python 3 code
def _check_dups(self, qubits):
        squbits = set(qubits)
        if len(squbits) != len(qubits):
            raise QiskitError("duplicate qubit arguments")

Response: Raise exception if list of qubits contains duplicates.


Instruction:
How would you explain what the following Python 3 function does
def _check_qargs(self, qargs):
        if not all(isinstance(i, tuple) and
                   isinstance(i[0], QuantumRegister) and
                   isinstance(i[1], int) for i in qargs):
            raise QiskitError("qarg not (QuantumRegister, int) tuple")
        if not all(self.has_register(i[0]) for i in qargs):
            raise QiskitError("register not in this circuit")
        for qubit in qargs:
            qubit[0].check_range(qubit[1])

Response: Raise exception if a qarg is not in this circuit or bad format.


Instruction:
How would you explain what the following Python 3 function does
def _check_cargs(self, cargs):
        if not all(isinstance(i, tuple) and
                   isinstance(i[0], ClassicalRegister) and
                   isinstance(i[1], int) for i in cargs):
            raise QiskitError("carg not (ClassicalRegister, int) tuple")
        if not all(self.has_register(i[0]) for i in cargs):
            raise QiskitError("register not in this circuit")
        for clbit in cargs:
            clbit[0].check_range(clbit[1])

Response: Raise exception if clbit is not in this circuit or bad format.


Instruction:
Here you have a function in Python 3, explain what it does
def decompose(self):
        from qiskit.transpiler.passes.decompose import Decompose
        from qiskit.converters.circuit_to_dag import circuit_to_dag
        from qiskit.converters.dag_to_circuit import dag_to_circuit
        pass_ = Decompose()
        decomposed_dag = pass_.run(circuit_to_dag(self))
        return dag_to_circuit(decomposed_dag)

Response: Call a decomposition pass on this circuit and return a QuantumCircuit one level decomposed


Instruction:
How would you explain what the following Python 3 function does
def _check_compatible_regs(self, rhs):
        list1 = self.qregs + self.cregs
        list2 = rhs.qregs + rhs.cregs
        for element1 in list1:
            for element2 in list2:
                if element2.name == element1.name:
                    if element1 != element2:
                        raise QiskitError("circuits are not compatible")

Response: Raise exception if the circuits are defined on incompatible registers


Instruction:
How would you implement a function in Python 3 that
returns the OpenQASM string for the current state of the object.

Response:
def qasm(self):
        """Return OpenQASM string."""
        string_temp = self.header + "\n"
        string_temp += self.extension_lib + "\n"
        for register in self.qregs:
            string_temp += register.qasm() + "\n"
        for register in self.cregs:
            string_temp += register.qasm() + "\n"
        for instruction, qargs, cargs in self.data:
            if instruction.name == 'measure':
                qubit = qargs[0]
                clbit = cargs[0]
                string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(),
                                                           qubit[0].name, qubit[1],
                                                           clbit[0].name, clbit[1])
            else:
                string_temp += "%s %s;\n" % (instruction.qasm(),
                                             ",".join(["%s[%d]" % (j[0].name, j[1])
                                                       for j in qargs + cargs]))
        return string_temp


Instruction:
Implement a Python 3 function for
drawing the quantum circuit with the specified parameters.

Response:
def draw(self, scale=0.7, filename=None, style=None, output='text',
             interactive=False, line_length=None, plot_barriers=True,
             reverse_bits=False, justify=None):
        """Draw the quantum circuit

        Using the output parameter you can specify the format. The choices are:
        0. text: ASCII art string
        1. latex: high-quality images, but heavy external software dependencies
        2. matplotlib: purely in Python with no external dependencies

        Defaults to an overcomplete basis, in order to not alter gates.

        Args:
            scale (float): scale of image to draw (shrink if < 1)
            filename (str): file path to save image to
            style (dict or str): dictionary of style or file name of style
                file. You can refer to the
                :ref:`Style Dict Doc <style-dict-doc>` for more information
                on the contents.
            output (str): Select the output method to use for drawing the
                circuit. Valid choices are `text`, `latex`, `latex_source`,
                `mpl`.
            interactive (bool): when set true show the circuit in a new window
                (for `mpl` this depends on the matplotlib backend being used
                supporting this). Note when used with either the `text` or the
                `latex_source` output type this has no effect and will be
                silently ignored.
            line_length (int): sets the length of the lines generated by `text`
            reverse_bits (bool): When set to True reverse the bit order inside
                registers for the output visualization.
            plot_barriers (bool): Enable/disable drawing barriers in the output
                circuit. Defaults to True.
            justify (string): Options are `left`, `right` or `none`, if anything
                else is supplied it defaults to left justified. It refers to where
                gates should be placed in the output circuit if there is an option.
                `none` results in each gate being placed in its own column. Currently
                only supported by text drawer.

        Returns:
            PIL.Image or matplotlib.figure or str or TextDrawing:
                * PIL.Image: (output `latex`) an in-memory representation of the
                  image of the circuit diagram.
                * matplotlib.figure: (output `mpl`) a matplotlib figure object
                  for the circuit diagram.
                * str: (output `latex_source`). The LaTeX source code.
                * TextDrawing: (output `text`). A drawing that can be printed as
                  ascii art

        Raises:
            VisualizationError: when an invalid output method is selected
        """
        from qiskit.tools import visualization
        return visualization.circuit_drawer(self, scale=scale,
                                            filename=filename, style=style,
                                            output=output,
                                            interactive=interactive,
                                            line_length=line_length,
                                            plot_barriers=plot_barriers,
                                            reverse_bits=reverse_bits,
                                            justify=justify)


Instruction:
Can you generate the documentation for the following Python 3 function
def size(self):
        gate_ops = 0
        for instr, _, _ in self.data:
            if instr.name not in ['barrier', 'snapshot']:
                gate_ops += 1
        return gate_ops

Response: Returns the number of gate operations in circuit.


Instruction:
How would you explain what the following Python 3 function does
def width(self):
        return sum(reg.size for reg in self.qregs+self.cregs)

Response: Return number of qubits plus clbits in circuit.


Instruction:
Can you generate the documentation for the following Python 3 function
def count_ops(self):
        count_ops = {}
        for instr, _, _ in self.data:
            if instr.name in count_ops.keys():
                count_ops[instr.name] += 1
            else:
                count_ops[instr.name] = 1
        return count_ops

Response: Count each operation kind in the circuit.


Instruction:
How would you implement a function in Python 3 that
returns the number of connected components in the current state of the cbits in the current state of the cbits in the current state of the cbits in the current state of the cbits in the current state of the cbits.

Response:
def num_connected_components(self, unitary_only=False):
        """How many non-entangled subcircuits can the circuit be factored to.

        Args:
            unitary_only (bool): Compute only unitary part of graph.

        Returns:
            int: Number of connected components in circuit.
        """
        # Convert registers to ints (as done in depth).
        reg_offset = 0
        reg_map = {}

        if unitary_only:
            regs = self.qregs
        else:
            regs = self.qregs+self.cregs

        for reg in regs:
            reg_map[reg.name] = reg_offset
            reg_offset += reg.size
        # Start with each qubit or cbit being its own subgraph.
        sub_graphs = [[bit] for bit in range(reg_offset)]

        num_sub_graphs = len(sub_graphs)

        # Here we are traversing the gates and looking to see
        # which of the sub_graphs the gate joins together.
        for instr, qargs, cargs in self.data:
            if unitary_only:
                args = qargs
                num_qargs = len(args)
            else:
                args = qargs+cargs
                num_qargs = len(args) + (1 if instr.control else 0)

            if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']:
                graphs_touched = []
                num_touched = 0
                # Controls necessarily join all the cbits in the
                # register that they use.
                if instr.control and not unitary_only:
                    creg = instr.control[0]
                    creg_int = reg_map[creg.name]
                    for coff in range(creg.size):
                        temp_int = creg_int+coff
                        for k in range(num_sub_graphs):
                            if temp_int in sub_graphs[k]:
                                graphs_touched.append(k)
                                num_touched += 1
                                break

                for item in args:
                    reg_int = reg_map[item[0].name]+item[1]
                    for k in range(num_sub_graphs):
                        if reg_int in sub_graphs[k]:
                            if k not in graphs_touched:
                                graphs_touched.append(k)
                                num_touched += 1
                                break

                # If the gate touches more than one subgraph
                # join those graphs together and return
                # reduced number of subgraphs
                if num_touched > 1:
                    connections = []
                    for idx in graphs_touched:
                        connections.extend(sub_graphs[idx])
                    _sub_graphs = []
                    for idx in range(num_sub_graphs):
                        if idx not in graphs_touched:
                            _sub_graphs.append(sub_graphs[idx])
                    _sub_graphs.append(connections)
                    sub_graphs = _sub_graphs
                    num_sub_graphs -= (num_touched-1)
            # Cannot go lower than one so break
            if num_sub_graphs == 1:
                break
        return num_sub_graphs


Instruction:
Write a Python 3 script to
assign parameters to values yielding a new circuit.

Response:
def bind_parameters(self, value_dict):
        """Assign parameters to values yielding a new circuit.

        Args:
            value_dict (dict): {parameter: value, ...}

        Raises:
            QiskitError: If value_dict contains parameters not present in the circuit

        Returns:
            QuantumCircuit: copy of self with assignment substitution.
        """
        new_circuit = self.copy()

        if value_dict.keys() > self.parameters:
            raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format(
                [str(p) for p in value_dict.keys() - self.parameters]))

        for parameter, value in value_dict.items():
            new_circuit._bind_parameter(parameter, value)
        # clear evaluated expressions
        for parameter in value_dict:
            del new_circuit._parameter_table[parameter]
        return new_circuit


Instruction:
How would you code a function in Python 3 to
assign a parameter value to matching instructions in - place.

Response:
def _bind_parameter(self, parameter, value):
        """Assigns a parameter value to matching instructions in-place."""
        for (instr, param_index) in self._parameter_table[parameter]:
            instr.params[param_index] = value


Instruction:
Can you generate the documentation for the following Python 3 function
def pulse_drawer(samples, duration, dt=None, interp_method='None',
                 filename=None, interactive=False,
                 dpi=150, nop=1000, size=(6, 5)):
    """Plot the interpolated envelope of pulse

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

    try:
        from matplotlib import pyplot as plt
    except ImportError:
        raise ImportError('pulse_drawer need matplotlib. '
                          'Run "pip install matplotlib" before.')

    if dt:
        _dt = dt
    else:
        _dt = 1

    re_y = np.real(samples)
    im_y = np.imag(samples)

    image = plt.figure(figsize=size)
    ax0 = image.add_subplot(111)

    if interp_method == 'CubicSpline':
        # spline interpolation, use mid-point of dt
        time = np.arange(0, duration + 1) * _dt + 0.5 * _dt
        cs_ry = CubicSpline(time[:-1], re_y)
        cs_iy = CubicSpline(time[:-1], im_y)

        _time = np.linspace(0, duration * _dt, nop)
        _re_y = cs_ry(_time)
        _im_y = cs_iy(_time)
    elif interp_method == 'None':
        # pseudo-DAC output
        time = np.arange(0, duration + 1) * _dt

        _time = np.r_[time[0], np.repeat(time[1:-1], 2), time[-1]]
        _re_y = np.repeat(re_y, 2)
        _im_y = np.repeat(im_y, 2)
    else:
        raise QiskitError('Invalid interpolation method "%s"' % interp_method)

    # plot
    ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time),
                     facecolor='red', alpha=0.3,
                     edgecolor='red', linewidth=1.5,
                     label='real part')
    ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time),
                     facecolor='blue', alpha=0.3,
                     edgecolor='blue', linewidth=1.5,
                     label='imaginary part')

    ax0.set_xlim(0, duration * _dt)
    ax0.grid(b=True, linestyle='-')
    ax0.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center',
               ncol=2, frameon=False, fontsize=14)

    if filename:
        image.savefig(filename, dpi=dpi, bbox_inches='tight')

    plt.close(image)

    if image and interactive:
        plt.show(image)

    return image

Response: Plot the interpolated envelope of a complex pulse.


Instruction:
Can you write a function in Python 3 where it
searches for SWAPs which allow for application of largest number of gates.

Response:
def _search_forward_n_swaps(layout, gates, coupling_map,
                            depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
    """Search for SWAPs which allow for application of largest number of gates.

    Arguments:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap of the target backend.
        depth (int): Number of SWAP layers to search before choosing a result.
        width (int): Number of SWAPs to consider at each layer.
    Returns:
        dict: Describes solution step found.
            layout (Layout): Virtual to physical qubit map after SWAPs.
            gates_remaining (list): Gates that could not be mapped.
            gates_mapped (list): Gates that were mapped, including added SWAPs.

    """

    gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)

    base_step = {'layout': layout,
                 'swaps_added': 0,
                 'gates_mapped': gates_mapped,
                 'gates_remaining': gates_remaining}

    if not gates_remaining or depth == 0:
        return base_step

    possible_swaps = coupling_map.get_edges()

    def _score_swap(swap):
        """Calculate the relative score for a given SWAP."""
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        return _calc_layout_distance(gates, coupling_map, trial_layout)

    ranked_swaps = sorted(possible_swaps, key=_score_swap)

    best_swap, best_step = None, None
    for swap in ranked_swaps[:width]:
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
                                            coupling_map, depth - 1, width)

        # ranked_swaps already sorted by distance, so distance is the tie-breaker.
        if best_swap is None or _score_step(next_step) > _score_step(best_step):
            best_swap, best_step = swap, next_step

    best_swap_gate = _swap_ops_from_edge(best_swap, layout)
    return {
        'layout': best_step['layout'],
        'swaps_added': 1 + best_step['swaps_added'],
        'gates_remaining': best_step['gates_remaining'],
        'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
    }


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _map_free_gates(layout, gates, coupling_map):

    blocked_qubits = set()

    mapped_gates = []
    remaining_gates = []

    for gate in gates:
        # Gates without a partition (barrier, snapshot, save, load, noise) may
        # still have associated qubits. Look for them in the qargs.
        if not gate['partition']:
            qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs

            if not qubits:
                continue

            if blocked_qubits.intersection(qubits):
                blocked_qubits.update(qubits)
                remaining_gates.append(gate)
            else:
                mapped_gate = _transform_gate_for_layout(gate, layout)
                mapped_gates.append(mapped_gate)
            continue

        qubits = gate['partition'][0]

        if blocked_qubits.intersection(qubits):
            blocked_qubits.update(qubits)
            remaining_gates.append(gate)
        elif len(qubits) == 1:
            mapped_gate = _transform_gate_for_layout(gate, layout)
            mapped_gates.append(mapped_gate)
        elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
            mapped_gate = _transform_gate_for_layout(gate, layout)
            mapped_gates.append(mapped_gate)
        else:
            blocked_qubits.update(qubits)
            remaining_gates.append(gate)

    return mapped_gates, remaining_gates

Response: Map all gates that can be executed on the current layout to the new layout.


Instruction:
Implement a Python 3 function for
calculating the distance between two - qubit pairs in each CNOT in gates based on the layout and the coupling.

Response:
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
    """Return the sum of the distances of two-qubit pairs in each CNOT in gates
    according to the layout and the coupling.
    """

    if max_gates is None:
        max_gates = 50 + 10 * len(coupling_map.physical_qubits)

    return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
               for gate in gates[:max_gates]
               if gate['partition'] and len(gate['partition'][0]) == 2)


Instruction:
Implement a Python 3 function for
returning the score of a step.

Response:
def _score_step(step):

    """Count the mapped two-qubit gates, less the number of added SWAPs."""
    # Each added swap will add 3 ops to gates_mapped, so subtract 3.
    return len([g for g in step['gates_mapped']
                if len(g.qargs) == 2]) - 3 * step['swaps_added']


Instruction:
Can you create a Python 3 function that
returns a copy of source_dag with metadata but empty.

Response:
def _copy_circuit_metadata(source_dag, coupling_map):
    """Return a copy of source_dag with metadata but empty.
    Generate only a single qreg in the output DAG, matching the size of the
    coupling_map."""

    target_dag = DAGCircuit()
    target_dag.name = source_dag.name

    for creg in source_dag.cregs.values():
        target_dag.add_creg(creg)

    device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
    target_dag.add_qreg(device_qreg)

    return target_dag


Instruction:
How would you explain what the following Python 3 function does
def _transform_gate_for_layout(gate, layout):

    mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0])

    # Workaround until #1816, apply mapped to qargs to both DAGNode and op
    device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
    mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs]
    mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs

    mapped_op_node.pop('name')

    return mapped_op_node

Response: Return op implementing a virtual gate on given layout.


Instruction:
Here you have a function in Python 3, explain what it does
def _swap_ops_from_edge(edge, layout):

    device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
    qreg_edge = [(device_qreg, i) for i in edge]

    # TODO shouldn't be making other nodes not by the DAG!!
    return [
        DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'})
    ]

Response: Generate list of ops to implement a SWAP gate along a coupling edge.


Instruction:
Here you have a function in Python 3, explain what it does
def run(self, dag):
        coupling_map = self._coupling_map
        ordered_virtual_gates = list(dag.serial_layers())

        if self.initial_layout is None:
            if self.property_set["layout"]:
                self.initial_layout = self.property_set["layout"]
            else:
                self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())

        if len(dag.qubits()) != len(self.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        mapped_gates = []
        layout = self.initial_layout.copy()
        gates_remaining = ordered_virtual_gates.copy()

        while gates_remaining:
            best_step = _search_forward_n_swaps(layout, gates_remaining,
                                                coupling_map)

            layout = best_step['layout']
            gates_mapped = best_step['gates_mapped']
            gates_remaining = best_step['gates_remaining']

            mapped_gates.extend(gates_mapped)

        # Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
        mapped_dag = _copy_circuit_metadata(dag, coupling_map)

        for node in mapped_gates:
            mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs)

        return mapped_dag

Response: This method runs one pass of the lookahead mapper on the given DAG.


Instruction:
Can you create a Python 3 function that
adds a physical qubit to the coupling graph as a node.

Response:
def add_physical_qubit(self, physical_qubit):
        """Add a physical qubit to the coupling graph as a node.

        physical_qubit (int): An integer representing a physical qubit.

        Raises:
            CouplingError: if trying to add duplicate qubit
        """
        if not isinstance(physical_qubit, int):
            raise CouplingError("Physical qubits should be integers.")
        if physical_qubit in self.physical_qubits:
            raise CouplingError(
                "The physical qubit %s is already in the coupling graph" % physical_qubit)
        self.graph.add_node(physical_qubit)
        self._dist_matrix = None  # invalidate
        self._qubit_list = None


Instruction:
Create a Python 3 function to
add a directed edge to the coupling graph.

Response:
def add_edge(self, src, dst):
        """
        Add directed edge to coupling graph.

        src (int): source physical qubit
        dst (int): destination physical qubit
        """
        if src not in self.physical_qubits:
            self.add_physical_qubit(src)
        if dst not in self.physical_qubits:
            self.add_physical_qubit(dst)
        self.graph.add_edge(src, dst)
        self._dist_matrix = None


Instruction:
Make a summary of the following Python 3 code
def subgraph(self, nodelist):
        subcoupling = CouplingMap()
        subcoupling.graph = self.graph.subgraph(nodelist)
        for node in nodelist:
            if node not in subcoupling.physical_qubits:
                subcoupling.add_physical_qubit(node)
        return subcoupling

Response: Return a CouplingMap object for a subgraph of self.


Instruction:
Can you generate the documentation for the following Python 3 function
def physical_qubits(self):
        if self._qubit_list is None:
            self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes])
        return self._qubit_list

Response: Returns a sorted list of physical_qubits


Instruction:
Can you create a Python 3 function that
tests if the graph is connected.

Response:
def is_connected(self):
        """
        Test if the graph is connected.

        Return True if connected, False otherwise
        """
        try:
            return nx.is_weakly_connected(self.graph)
        except nx.exception.NetworkXException:
            return False


Instruction:
Can you tell what is the following Python 3 function doing
def _compute_distance_matrix(self):
        if not self.is_connected():
            raise CouplingError("coupling graph not connected")
        lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True))
        lengths = dict(lengths)
        size = len(lengths)
        cmap = np.zeros((size, size))
        for idx in range(size):
            cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter(
                lengths[idx].values(), dtype=int)
        self._dist_matrix = cmap

Response: Compute the full distance matrix on pairs of nodes.


Instruction:
Write a Python 3 script to
return the undirected distance between two physical qubits.

Response:
def distance(self, physical_qubit1, physical_qubit2):
        """Returns the undirected distance between physical_qubit1 and physical_qubit2.

        Args:
            physical_qubit1 (int): A physical qubit
            physical_qubit2 (int): Another physical qubit

        Returns:
            int: The undirected distance

        Raises:
            CouplingError: if the qubits do not exist in the CouplingMap
        """
        if physical_qubit1 not in self.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (physical_qubit1,))
        if physical_qubit2 not in self.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (physical_qubit2,))
        if self._dist_matrix is None:
            self._compute_distance_matrix()
        return self._dist_matrix[physical_qubit1, physical_qubit2]


Instruction:
Write a Python 3 function that can
deprecate - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag

Response:
def transpile_dag(dag, basis_gates=None, coupling_map=None,
                  initial_layout=None, seed_mapper=None, pass_manager=None):
    """Deprecated - Use qiskit.compiler.transpile for transpiling from
    circuits to circuits.
    Transform a dag circuit into another dag circuit
    (transpile), through consecutive passes on the dag.

    Args:
        dag (DAGCircuit): dag circuit to transform via transpilation
        basis_gates (list[str]): list of basis gate names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): A graph of coupling::

            [
             [control0(int), target0(int)],
             [control1(int), target1(int)],
            ]

            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}

        initial_layout (Layout or None): A layout object
        seed_mapper (int): random seed_mapper for the swap mapper
        pass_manager (PassManager): pass manager instance for the transpilation process
            If None, a default set of passes are run.
            Otherwise, the passes defined in it will run.
            If contains no passes in it, no dag transformations occur.

    Returns:
        DAGCircuit: transformed dag
    """
    warnings.warn("transpile_dag has been deprecated and will be removed in the "
                  "0.9 release. Circuits can be transpiled directly to other "
                  "circuits with the transpile function.", DeprecationWarning)

    if basis_gates is None:
        basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']

    if pass_manager is None:
        # default set of passes

        # if a coupling map is given compile to the map
        if coupling_map:
            pass_manager = default_pass_manager(basis_gates,
                                                CouplingMap(coupling_map),
                                                initial_layout,
                                                seed_transpiler=seed_mapper)
        else:
            pass_manager = default_pass_manager_simulator(basis_gates)

    # run the passes specified by the pass manager
    # TODO return the property set too. See #1086
    name = dag.name
    circuit = dag_to_circuit(dag)
    circuit = pass_manager.run(circuit)
    dag = circuit_to_dag(circuit)
    dag.name = name

    return dag


Instruction:
Here you have a function in Python 3, explain what it does
def cu1(self, theta, ctl, tgt):
    return self.append(Cu1Gate(theta), [ctl, tgt], [])

Response: Apply cu1 from ctl to tgt with angle theta.


Instruction:
Here you have a function in Python 3, explain what it does
def add(self, gate, qargs, cargs):
        if not isinstance(gate, Instruction):
            raise QiskitError("attempt to add non-Instruction" +
                              " to InstructionSet")
        self.instructions.append(gate)
        self.qargs.append(qargs)
        self.cargs.append(cargs)

Response: Add an instruction and its context.


Instruction:
How would you explain what the following Python 3 function does
def q_if(self, *qregs):
        for gate in self.instructions:
            gate.q_if(*qregs)
        return self

Response: Add controls to all instructions.


Instruction:
Write a Python 3 script for
adding classical control register to all instructions.

Response:
def c_if(self, classical, val):
        """Add classical control register to all instructions."""
        for gate in self.instructions:
            gate.c_if(classical, val)
        return self


Instruction:
Write a Python 3 script to
subscribe to an event so when it s emitted all the callbacks subscribed will be executed.

Response:
def subscribe(self, event, callback):
        """Subscribes to an event, so when it's emitted all the callbacks subscribed,
        will be executed. We are not allowing double registration.

        Args
            event (string): The event to subscribed in the form of:
                            "terra.<component>.<method>.<action>"
            callback (callable): The callback that will be executed when an event is
                                  emitted.
        """
        if not callable(callback):
            raise QiskitError("Callback is not a callable!")

        if event not in self._subscribers:
            self._subscribers[event] = []

        new_subscription = self._Subscription(event, callback)
        if new_subscription in self._subscribers[event]:
            # We are not allowing double subscription
            return False

        self._subscribers[event].append(new_subscription)
        return True


Instruction:
How would you explain what the following Python 3 function does
def dispatch(self, event, *args, **kwargs):
        # No event, no subscribers.
        if event not in self._subscribers:
            return

        for subscriber in self._subscribers[event]:
            subscriber.callback(*args, **kwargs)

Response: Emits an event if there are any subscribers.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def publish(self, event, *args, **kwargs):
        return self._broker.dispatch(event, *args, **kwargs)

Response: Triggers an event and associates some data to it.


Instruction:
Write a Python 3 script for
applying initialize to circuit.

Response:
def initialize(self, params, qubits):
    """Apply initialize to circuit."""
    if isinstance(qubits, QuantumRegister):
        qubits = qubits[:]
    else:
        qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0]
    return self.append(Initialize(params), qubits)


Instruction:
Here you have a function in Python 3, explain what it does
def _define(self):
        # call to generate the circuit that takes the desired vector to zero
        disentangling_circuit = self.gates_to_uncompute()

        # invert the circuit to create the desired vector from zero (assuming
        # the qubits are in the zero state)
        initialize_instr = disentangling_circuit.to_instruction().inverse()

        q = QuantumRegister(self.num_qubits, 'q')
        initialize_circuit = QuantumCircuit(q, name='init_def')
        for qubit in q:
            initialize_circuit.append(Reset(), [qubit])
        initialize_circuit.append(initialize_instr, q[:])

        self.definition = initialize_circuit.data

Response:
Calculate a subcircuit that implements this initialization
        Implements a recursive initialization algorithm from Synthesis of Quantum Logic Circuits Shende Bullock Markov
        https://arxiv. org / abs / quant - ph/0406176v5.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def gates_to_uncompute(self):
        q = QuantumRegister(self.num_qubits)
        circuit = QuantumCircuit(q, name='disentangler')

        # kick start the peeling loop, and disentangle one-by-one from LSB to MSB
        remaining_param = self.params

        for i in range(self.num_qubits):
            # work out which rotations must be done to disentangle the LSB
            # qubit (we peel away one qubit at a time)
            (remaining_param,
             thetas,
             phis) = Initialize._rotations_to_disentangle(remaining_param)

            # perform the required rotations to decouple the LSB qubit (so that
            # it can be "factored" out, leaving a shorter amplitude vector to peel away)
            rz_mult = self._multiplex(RZGate, phis)
            ry_mult = self._multiplex(RYGate, thetas)
            circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits])
            circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits])
        return circuit

Response: Create a circuit with gates that take the desired vector to zero.


Instruction:
Can you generate the documentation for the following Python 3 function
def _rotations_to_disentangle(local_param):
        remaining_vector = []
        thetas = []
        phis = []

        param_len = len(local_param)

        for i in range(param_len // 2):
            # Ry and Rz rotations to move bloch vector from 0 to "imaginary"
            # qubit
            # (imagine a qubit state signified by the amplitudes at index 2*i
            # and 2*(i+1), corresponding to the select qubits of the
            # multiplexor being in state |i>)
            (remains,
             add_theta,
             add_phi) = Initialize._bloch_angles(local_param[2 * i: 2 * (i + 1)])

            remaining_vector.append(remains)

            # rotations for all imaginary qubits of the full vector
            # to move from where it is to zero, hence the negative sign
            thetas.append(-add_theta)
            phis.append(-add_phi)

        return remaining_vector, thetas, phis

Response: This method is used to work out the Ry and Rz rotations used to disentangle the LSB qubit.


Instruction:
Here you have a function in Python 3, explain what it does
def _bloch_angles(pair_of_complex):
        [a_complex, b_complex] = pair_of_complex
        # Force a and b to be complex, as otherwise numpy.angle might fail.
        a_complex = complex(a_complex)
        b_complex = complex(b_complex)
        mag_a = np.absolute(a_complex)
        final_r = float(np.sqrt(mag_a ** 2 + np.absolute(b_complex) ** 2))
        if final_r < _EPS:
            theta = 0
            phi = 0
            final_r = 0
            final_t = 0
        else:
            theta = float(2 * np.arccos(mag_a / final_r))
            a_arg = np.angle(a_complex)
            b_arg = np.angle(b_complex)
            final_t = a_arg + b_arg
            phi = b_arg - a_arg

        return final_r * np.exp(1.J * final_t / 2), theta, phi

Response: Static method to work out the angle between two sets of elements.


Instruction:
Given the following Python 3 function, write the documentation
def _multiplex(self, target_gate, list_of_angles):
        list_len = len(list_of_angles)
        local_num_qubits = int(math.log2(list_len)) + 1

        q = QuantumRegister(local_num_qubits)
        circuit = QuantumCircuit(q, name="multiplex" + local_num_qubits.__str__())

        lsb = q[0]
        msb = q[local_num_qubits - 1]

        # case of no multiplexing: base case for recursion
        if local_num_qubits == 1:
            circuit.append(target_gate(list_of_angles[0]), [q[0]])
            return circuit

        # calc angle weights, assuming recursion (that is the lower-level
        # requested angles have been correctly implemented by recursion
        angle_weight = scipy.kron([[0.5, 0.5], [0.5, -0.5]],
                                  np.identity(2 ** (local_num_qubits - 2)))

        # calc the combo angles
        list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist()

        # recursive step on half the angles fulfilling the above assumption
        multiplex_1 = self._multiplex(target_gate, list_of_angles[0:(list_len // 2)])
        circuit.append(multiplex_1.to_instruction(), q[0:-1])

        # attach CNOT as follows, thereby flipping the LSB qubit
        circuit.append(CnotGate(), [msb, lsb])

        # implement extra efficiency from the paper of cancelling adjacent
        # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the
        # second lower-level multiplex)
        multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // 2):])
        if list_len > 1:
            circuit.append(multiplex_2.to_instruction().mirror(), q[0:-1])
        else:
            circuit.append(multiplex_2.to_instruction(), q[0:-1])

        # attach a final CNOT
        circuit.append(CnotGate(), [msb, lsb])

        return circuit

Response: Returns a recursive implementation of a multiplexor circuit with a decomposition based on the given target_gate and list of rotation angles.


Instruction:
Write a Python 3 function for
populating a Layout from a dictionary.

Response:
def from_dict(self, input_dict):
        """
        Populates a Layout from a dictionary.
        The dictionary must be a bijective mapping between
        virtual qubits (tuple) and physical qubits (int).

        Args:
            input_dict (dict):
                e.g.:
                {(QuantumRegister(3, 'qr'), 0): 0,
                 (QuantumRegister(3, 'qr'), 1): 1,
                 (QuantumRegister(3, 'qr'), 2): 2}

                Can be written more concisely as follows:

                virtual to physical:
                    {qr[0]: 0,
                     qr[1]: 1,
                     qr[2]: 2}

                physical to virtual:
                    {0: qr[0],
                     1: qr[1],
                     2: qr[2]}
        """
        # TODO (luciano): Remove this full block after 0.8.
        #  its here to support {("qr", 0): ("q", 0),...}
        if len(input_dict) >= 1:
            key = list(input_dict.keys())[0]
            value = input_dict[key]
            if (isinstance(key, tuple) and  # pylint: disable=too-many-boolean-expressions
                    len(key) == 2 and
                    isinstance(key[0], str) and
                    isinstance(key[1], int) and
                    isinstance(value, tuple) and
                    len(value) == 2 and
                    isinstance(key[0], str) and
                    isinstance(key[1], int)):
                warnings.warn("This form of dictionary (i.e. {(\"%s\",%s):(\"%s\",%s), ...} is "
                              "going to be deprecated after 0.8." % (key + value),
                              DeprecationWarning)
                qreg_names = {qubit[0] for qubit in input_dict.keys()}
                qregs = {}
                for qreg_name in qreg_names:
                    qregs[qreg_name] = QuantumRegister(
                        max([qubit[1] for qubit in input_dict.keys() if qubit[0] == qreg_name]) + 1,
                        qreg_name)
                new_input_dict = {}
                for key, value in input_dict.items():
                    new_input_dict[value[1]] = (qregs[key[0]], key[1])
                input_dict = new_input_dict

        for key, value in input_dict.items():
            virtual, physical = Layout.order_based_on_type(key, value)
            self._p2v[physical] = virtual
            if virtual is None:
                continue
            self._v2p[virtual] = physical