ketex = "<STR_LIT>"<EOL>if convention == "<STR_LIT>":<EOL><INDENT>self.xlabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.ylabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.zlabel = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>elif convention == "<STR_LIT>":<EOL><INDENT>self.xlabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.ylabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.zlabel = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>elif convention == "<STR_LIT>":<EOL><INDENT>self.xlabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.ylabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.zlabel = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>elif convention == "<STR_LIT>":<EOL><INDENT>self.xlabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.ylabel = ['<STR_LIT>', '<STR_LIT>']<EOL>self.zlabel = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>elif convention == "<STR_LIT>":<EOL><INDENT>self.xlabel = [ketex % "<STR_LIT>",<EOL>ketex % "<STR_LIT>"]<EOL>self.ylabel = [ketex % "<STR_LIT>", ketex %<EOL>"<STR_LIT>"]<EOL>self.zlabel = [ketex % "<STR_LIT>", ketex % "<STR_LIT>"]<EOL><DEDENT>elif convention == "<STR_LIT>":<EOL><INDENT>self.xlabel = [ketex % "<STR_LIT:D>", ketex % "<STR_LIT:A>"]<EOL>self.ylabel = [ketex % "<STR_LIT:L>", ketex % "<STR_LIT:R>"]<EOL>self.zlabel = [ketex % "<STR_LIT:H>", ketex % "<STR_LIT>"]<EOL><DEDENT>elif convention == "<STR_LIT>":<EOL><INDENT>self.ylabel = ["<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>self.zlabel = ["<STR_LIT>", "<STR_LIT>"]<EOL>self.xlabel = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>

Set x, y and z labels according to one of conventions.

        Args:
            convention (str):
                One of the following:
                    - "original"
                    - "xyz"
                    - "sx sy sz"
                    - "01"
                    - "polarization jones"
                    - "polarization jones letters"
                    see also: http://en.wikipedia.org/wiki/Jones_calculus
                    - "polarization stokes"
                    see also: http://en.wikipedia.org/wiki/Stokes_parameters
        Raises:
            Exception: If convention is not valid.


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


def add_points(self, points, meth='<STR_LIT:s>'):

if not isinstance(points[<NUM_LIT:0>], (list, np.ndarray)):<EOL><INDENT>points = [[points[<NUM_LIT:0>]], [points[<NUM_LIT:1>]], [points[<NUM_LIT:2>]]]<EOL><DEDENT>points = np.array(points)<EOL>if meth == '<STR_LIT:s>':<EOL><INDENT>if len(points[<NUM_LIT:0>]) == <NUM_LIT:1>:<EOL><INDENT>pnts = np.array([[points[<NUM_LIT:0>][<NUM_LIT:0>]],<EOL>[points[<NUM_LIT:1>][<NUM_LIT:0>]], [points[<NUM_LIT:2>][<NUM_LIT:0>]]])<EOL>pnts = np.append(pnts, points, axis=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>pnts = points<EOL><DEDENT>self.points.append(pnts)<EOL>self.point_style.append('<STR_LIT:s>')<EOL><DEDENT>elif meth == '<STR_LIT:l>':<EOL><INDENT>self.points.append(points)<EOL>self.point_style.append('<STR_LIT:l>')<EOL><DEDENT>else:<EOL><INDENT>self.points.append(points)<EOL>self.point_style.append('<STR_LIT:m>')<EOL><DEDENT>

Add a list of data points to bloch sphere.
        Args:
            points (array_like):
                Collection of data points.
            meth (str):
                Type of points to plot, use 'm' for multicolored, 'l' for points
                connected with a line.


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

Add a list of vectors to Bloch sphere.

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


def add_annotation(self, state_or_vector, text, **kwargs):

if isinstance(state_or_vector, (list, np.ndarray, tuple))and len(state_or_vector) == <NUM_LIT:3>:<EOL><INDENT>vec = state_or_vector<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>self.annotations.append({'<STR_LIT>': vec,<EOL>'<STR_LIT:text>': text,<EOL>'<STR_LIT>': kwargs})<EOL>

Add a text or LaTeX annotation to Bloch sphere,
        parametrized by a qubit state or a vector.

        Args:
            state_or_vector (array_like):
                Position for the annotation.
                Qobj of a qubit or a vector of 3 elements.
            text (str):
                Annotation text.
                You can use LaTeX, but remember to use raw string
                e.g. r"$\\langle x \\rangle$"
                or escape backslashes
                e.g. "$\\\\langle x \\\\rangle$".
            **kwargs:
                Options as for mplot3d.axes3d.text, including:
                fontsize, color, horizontalalignment, verticalalignment.
        Raises:
            Exception: If input not array_like or tuple.


self.render()<EOL>


if self._rendered:<EOL><INDENT>self.axes.clear()<EOL><DEDENT>self._rendered = True<EOL>if not self._ext_fig:<EOL><INDENT>self.fig = plt.figure(figsize=self.figsize)<EOL><DEDENT>if not self._ext_axes:<EOL><INDENT>self.axes = Axes3D(self.fig, azim=self.view[<NUM_LIT:0>], elev=self.view[<NUM_LIT:1>])<EOL><DEDENT>if self.background:<EOL><INDENT>self.axes.clear()<EOL>self.axes.set_xlim3d(-<NUM_LIT>, <NUM_LIT>)<EOL>self.axes.set_ylim3d(-<NUM_LIT>, <NUM_LIT>)<EOL>self.axes.set_zlim3d(-<NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>self.plot_axes()<EOL>self.axes.set_axis_off()<EOL>self.axes.set_xlim3d(-<NUM_LIT>, <NUM_LIT>)<EOL>self.axes.set_ylim3d(-<NUM_LIT>, <NUM_LIT>)<EOL>self.axes.set_zlim3d(-<NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>self.axes.grid(False)<EOL>self.plot_back()<EOL>self.plot_points()<EOL>self.plot_vectors()<EOL>self.plot_front()<EOL>self.plot_axes_labels()<EOL>self.plot_annotations()<EOL>self.axes.set_title(title, fontsize=self.font_size, y=<NUM_LIT>)<EOL>

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


u_angle = np.linspace(<NUM_LIT:0>, np.pi, <NUM_LIT>)<EOL>v_angle = np.linspace(<NUM_LIT:0>, np.pi, <NUM_LIT>)<EOL>x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))<EOL>y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))<EOL>z_dir = np.outer(np.ones(u_angle.shape[<NUM_LIT:0>]), np.cos(v_angle))<EOL>self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=<NUM_LIT:2>, cstride=<NUM_LIT:2>,<EOL>color=self.sphere_color, linewidth=<NUM_LIT:0>,<EOL>alpha=self.sphere_alpha)<EOL>self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=<NUM_LIT:5>, cstride=<NUM_LIT:5>,<EOL>color=self.frame_color,<EOL>alpha=self.frame_alpha)<EOL>self.axes.plot(<NUM_LIT:1.0> * np.cos(u_angle), <NUM_LIT:1.0> * np.sin(u_angle), zs=<NUM_LIT:0>, zdir='<STR_LIT:z>',<EOL>lw=self.frame_width, color=self.frame_color)<EOL>self.axes.plot(<NUM_LIT:1.0> * np.cos(u_angle), <NUM_LIT:1.0> * np.sin(u_angle), zs=<NUM_LIT:0>, zdir='<STR_LIT:x>',<EOL>lw=self.frame_width, color=self.frame_color)<EOL>


u_angle = np.linspace(-np.pi, <NUM_LIT:0>, <NUM_LIT>)<EOL>v_angle = np.linspace(<NUM_LIT:0>, np.pi, <NUM_LIT>)<EOL>x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))<EOL>y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))<EOL>z_dir = np.outer(np.ones(u_angle.shape[<NUM_LIT:0>]), np.cos(v_angle))<EOL>self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=<NUM_LIT:2>, cstride=<NUM_LIT:2>,<EOL>color=self.sphere_color, linewidth=<NUM_LIT:0>,<EOL>alpha=self.sphere_alpha)<EOL>self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=<NUM_LIT:5>, cstride=<NUM_LIT:5>,<EOL>color=self.frame_color,<EOL>alpha=self.frame_alpha)<EOL>self.axes.plot(<NUM_LIT:1.0> * np.cos(u_angle), <NUM_LIT:1.0> * np.sin(u_angle),<EOL>zs=<NUM_LIT:0>, zdir='<STR_LIT:z>', lw=self.frame_width,<EOL>color=self.frame_color)<EOL>self.axes.plot(<NUM_LIT:1.0> * np.cos(u_angle), <NUM_LIT:1.0> * np.sin(u_angle),<EOL>zs=<NUM_LIT:0>, zdir='<STR_LIT:x>', lw=self.frame_width,<EOL>color=self.frame_color)<EOL>


span = np.linspace(-<NUM_LIT:1.0>, <NUM_LIT:1.0>, <NUM_LIT:2>)<EOL>self.axes.plot(span, <NUM_LIT:0> * span, zs=<NUM_LIT:0>, zdir='<STR_LIT:z>', label='<STR_LIT:X>',<EOL>lw=self.frame_width, color=self.frame_color)<EOL>self.axes.plot(<NUM_LIT:0> * span, span, zs=<NUM_LIT:0>, zdir='<STR_LIT:z>', label='<STR_LIT:Y>',<EOL>lw=self.frame_width, color=self.frame_color)<EOL>self.axes.plot(<NUM_LIT:0> * span, span, zs=<NUM_LIT:0>, zdir='<STR_LIT:y>', label='<STR_LIT>',<EOL>lw=self.frame_width, color=self.frame_color)<EOL>


opts = {'<STR_LIT>': self.font_size,<EOL>'<STR_LIT>': self.font_color,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>self.axes.text(<NUM_LIT:0>, -self.xlpos[<NUM_LIT:0>], <NUM_LIT:0>, self.xlabel[<NUM_LIT:0>], **opts)<EOL>self.axes.text(<NUM_LIT:0>, -self.xlpos[<NUM_LIT:1>], <NUM_LIT:0>, self.xlabel[<NUM_LIT:1>], **opts)<EOL>self.axes.text(self.ylpos[<NUM_LIT:0>], <NUM_LIT:0>, <NUM_LIT:0>, self.ylabel[<NUM_LIT:0>], **opts)<EOL>self.axes.text(self.ylpos[<NUM_LIT:1>], <NUM_LIT:0>, <NUM_LIT:0>, self.ylabel[<NUM_LIT:1>], **opts)<EOL>self.axes.text(<NUM_LIT:0>, <NUM_LIT:0>, self.zlpos[<NUM_LIT:0>], self.zlabel[<NUM_LIT:0>], **opts)<EOL>self.axes.text(<NUM_LIT:0>, <NUM_LIT:0>, self.zlpos[<NUM_LIT:1>], self.zlabel[<NUM_LIT:1>], **opts)<EOL>for item in (self.axes.w_xaxis.get_ticklines() +<EOL>self.axes.w_xaxis.get_ticklabels()):<EOL><INDENT>item.set_visible(False)<EOL><DEDENT>for item in (self.axes.w_yaxis.get_ticklines() +<EOL>self.axes.w_yaxis.get_ticklabels()):<EOL><INDENT>item.set_visible(False)<EOL><DEDENT>for item in (self.axes.w_zaxis.get_ticklines() +<EOL>self.axes.w_zaxis.get_ticklabels()):<EOL><INDENT>item.set_visible(False)<EOL><DEDENT>


<EOL>for k in range(len(self.vectors)):<EOL><INDENT>xs3d = self.vectors[k][<NUM_LIT:1>] * np.array([<NUM_LIT:0>, <NUM_LIT:1>])<EOL>ys3d = -self.vectors[k][<NUM_LIT:0>] * np.array([<NUM_LIT:0>, <NUM_LIT:1>])<EOL>zs3d = self.vectors[k][<NUM_LIT:2>] * np.array([<NUM_LIT:0>, <NUM_LIT:1>])<EOL>color = self.vector_color[np.mod(k, len(self.vector_color))]<EOL>if self.vector_style == '<STR_LIT>':<EOL><INDENT>self.axes.plot(xs3d, ys3d, zs3d,<EOL>zs=<NUM_LIT:0>, zdir='<STR_LIT:z>', label='<STR_LIT>',<EOL>lw=self.vector_width, color=color)<EOL><DEDENT>else:<EOL><INDENT>arr = Arrow3D(xs3d, ys3d, zs3d,<EOL>mutation_scale=self.vector_mutation,<EOL>lw=self.vector_width,<EOL>arrowstyle=self.vector_style,<EOL>color=color)<EOL>self.axes.add_artist(arr)<EOL><DEDENT><DEDENT>


<EOL>for k in range(len(self.points)):<EOL><INDENT>num = len(self.points[k][<NUM_LIT:0>])<EOL>dist = [np.sqrt(self.points[k][<NUM_LIT:0>][j] ** <NUM_LIT:2> +<EOL>self.points[k][<NUM_LIT:1>][j] ** <NUM_LIT:2> +<EOL>self.points[k][<NUM_LIT:2>][j] ** <NUM_LIT:2>) for j in range(num)]<EOL>if any(abs(dist - dist[<NUM_LIT:0>]) / dist[<NUM_LIT:0>] > <NUM_LIT>):<EOL><INDENT>zipped = list(zip(dist, range(num)))<EOL>zipped.sort()  <EOL>dist, indperm = zip(*zipped)<EOL>indperm = np.array(indperm)<EOL><DEDENT>else:<EOL><INDENT>indperm = np.arange(num)<EOL><DEDENT>if self.point_style[k] == '<STR_LIT:s>':<EOL><INDENT>self.axes.scatter(<EOL>np.real(self.points[k][<NUM_LIT:1>][indperm]),<EOL>- np.real(self.points[k][<NUM_LIT:0>][indperm]),<EOL>np.real(self.points[k][<NUM_LIT:2>][indperm]),<EOL>s=self.point_size[np.mod(k, len(self.point_size))],<EOL>alpha=<NUM_LIT:1>,<EOL>edgecolor='<STR_LIT:none>',<EOL>zdir='<STR_LIT:z>',<EOL>color=self.point_color[np.mod(k, len(self.point_color))],<EOL>marker=self.point_marker[np.mod(k,<EOL>len(self.point_marker))])<EOL><DEDENT>elif self.point_style[k] == '<STR_LIT:m>':<EOL><INDENT>pnt_colors = np.array(self.point_color *<EOL>int(np.ceil(num /<EOL>float(len(self.point_color)))))<EOL>pnt_colors = pnt_colors[<NUM_LIT:0>:num]<EOL>pnt_colors = list(pnt_colors[indperm])<EOL>marker = self.point_marker[np.mod(k, len(self.point_marker))]<EOL>pnt_size = self.point_size[np.mod(k, len(self.point_size))]<EOL>self.axes.scatter(np.real(self.points[k][<NUM_LIT:1>][indperm]),<EOL>-np.real(self.points[k][<NUM_LIT:0>][indperm]),<EOL>np.real(self.points[k][<NUM_LIT:2>][indperm]),<EOL>s=pnt_size, alpha=<NUM_LIT:1>, edgecolor='<STR_LIT:none>',<EOL>zdir='<STR_LIT:z>', color=pnt_colors,<EOL>marker=marker)<EOL><DEDENT>elif self.point_style[k] == '<STR_LIT:l>':<EOL><INDENT>color = self.point_color[np.mod(k, len(self.point_color))]<EOL>self.axes.plot(np.real(self.points[k][<NUM_LIT:1>]),<EOL>-np.real(self.points[k][<NUM_LIT:0>]),<EOL>np.real(self.points[k][<NUM_LIT:2>]),<EOL>alpha=<NUM_LIT>, zdir='<STR_LIT:z>',<EOL>color=color)<EOL><DEDENT><DEDENT>


<EOL>for annotation in self.annotations:<EOL><INDENT>vec = annotation['<STR_LIT>']<EOL>opts = {'<STR_LIT>': self.font_size,<EOL>'<STR_LIT>': self.font_color,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>opts.update(annotation['<STR_LIT>'])<EOL>self.axes.text(vec[<NUM_LIT:1>], -vec[<NUM_LIT:0>], vec[<NUM_LIT:2>],<EOL>annotation['<STR_LIT:text>'], **opts)<EOL><DEDENT>


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

Display Bloch sphere and corresponding data sets.


def save(self, name=None, output='<STR_LIT>', dirc=None):

self.render()<EOL>if dirc:<EOL><INDENT>if not os.path.isdir(os.getcwd() + "<STR_LIT:/>" + str(dirc)):<EOL><INDENT>os.makedirs(os.getcwd() + "<STR_LIT:/>" + str(dirc))<EOL><DEDENT><DEDENT>if name is None:<EOL><INDENT>if dirc:<EOL><INDENT>self.fig.savefig(os.getcwd() + "<STR_LIT:/>" + str(dirc) + '<STR_LIT>' +<EOL>str(self.savenum) + '<STR_LIT:.>' + output)<EOL><DEDENT>else:<EOL><INDENT>self.fig.savefig(os.getcwd() + '<STR_LIT>' + str(self.savenum) +<EOL>'<STR_LIT:.>' + output)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.fig.savefig(name)<EOL><DEDENT>self.savenum += <NUM_LIT:1><EOL>if self.fig:<EOL><INDENT>plt.close(self.fig)<EOL><DEDENT>

Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
        Args:
            name (str):
                Name of saved image. Must include path and format as well.
                i.e. '/Users/Paul/Desktop/bloch.png'
                This overrides the 'format' and 'dirc' arguments.
            output (str):
                Format of output image.
            dirc (str):
                Directory for output images. Defaults to current working directory.


rho = np.asarray(quantum_state)<EOL>if rho.ndim == <NUM_LIT:1>:<EOL><INDENT>rho = np.outer(rho, np.conj(rho))<EOL><DEDENT>shape = np.shape(rho)<EOL>if len(shape) != <NUM_LIT:2> or shape[<NUM_LIT:0>] != shape[<NUM_LIT:1>]:<EOL><INDENT>raise VisualizationError("<STR_LIT>")<EOL><DEDENT>num = int(np.log2(rho.shape[<NUM_LIT:0>]))<EOL>if <NUM_LIT:2> ** num != rho.shape[<NUM_LIT:0>]:<EOL><INDENT>raise VisualizationError("<STR_LIT>")<EOL><DEDENT>return rho<EOL>

Validates the input to state visualization functions.

    Args:
        quantum_state (ndarray): Input state / density matrix.
    Returns:
        rho: A 2d numpy array for the density matrix.
    Raises:
        VisualizationError: Invalid input.


background = PIL.Image.new(image.mode, image.size, image.getpixel((<NUM_LIT:0>, <NUM_LIT:0>)))<EOL>diff = PIL.ImageChops.difference(image, background)<EOL>diff = PIL.ImageChops.add(diff, diff, <NUM_LIT>, -<NUM_LIT:100>)<EOL>bbox = diff.getbbox()<EOL>if bbox:<EOL><INDENT>image = image.crop(bbox)<EOL><DEDENT>return image<EOL>

Trim a PIL image and remove white space.


def _get_layered_instructions(circuit, reverse_bits=False, justify=None):

if justify:<EOL><INDENT>justify = justify.lower()<EOL><DEDENT>justify = justify if justify in ('<STR_LIT:right>', '<STR_LIT:none>') else '<STR_LIT:left>'<EOL>dag = circuit_to_dag(circuit)<EOL>ops = []<EOL>qregs = []<EOL>cregs = []<EOL>for qreg in dag.qregs.values():<EOL><INDENT>qregs += [(qreg, bitno) for bitno in range(qreg.size)]<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>cregs += [(creg, bitno) for bitno in range(creg.size)]<EOL><DEDENT>if justify == '<STR_LIT:none>':<EOL><INDENT>for node in dag.topological_op_nodes():<EOL><INDENT>ops.append([node])<EOL><DEDENT><DEDENT>if justify == '<STR_LIT:left>':<EOL><INDENT>for dag_layer in dag.layers():<EOL><INDENT>layers = []<EOL>current_layer = []<EOL>dag_nodes = dag_layer['<STR_LIT>'].op_nodes()<EOL>dag_nodes.sort(key=lambda nd: nd._node_id)<EOL>for node in dag_nodes:<EOL><INDENT>multibit_gate = len(node.qargs) + len(node.cargs) > <NUM_LIT:1><EOL>if multibit_gate:<EOL><INDENT>gate_span = _get_gate_span(qregs, node)<EOL>all_indices = []<EOL>for check_node in dag_nodes:<EOL><INDENT>if check_node != node:<EOL><INDENT>all_indices += _get_gate_span(qregs, check_node)<EOL><DEDENT><DEDENT>if any(i in gate_span for i in all_indices):<EOL><INDENT>layers.append([node])<EOL><DEDENT>else:<EOL><INDENT>current_layer.append(node)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>current_layer.append(node)<EOL><DEDENT><DEDENT>if current_layer:<EOL><INDENT>layers.append(current_layer)<EOL><DEDENT>ops += layers<EOL><DEDENT><DEDENT>if justify == '<STR_LIT:right>':<EOL><INDENT>dag_layers = []<EOL>for dag_layer in dag.layers():<EOL><INDENT>dag_layers.append(dag_layer)<EOL><DEDENT>dag_layers.reverse()<EOL>layer_dicts = [{}]<EOL>for dag_layer in dag_layers:<EOL><INDENT>dag_instructions = dag_layer['<STR_LIT>'].op_nodes()<EOL>dag_instructions.sort(key=lambda nd: nd._node_id)<EOL>for instruction_node in dag_instructions:<EOL><INDENT>gate_span = _get_gate_span(qregs, instruction_node)<EOL>added = False<EOL>for i in range(len(layer_dicts)):<EOL><INDENT>curr_dict = layer_dicts[-<NUM_LIT:1> - i]<EOL>if any(index in curr_dict for index in gate_span):<EOL><INDENT>added = True<EOL>if i == <NUM_LIT:0>:<EOL><INDENT>new_dict = {}<EOL>for index in gate_span:<EOL><INDENT>new_dict[index] = instruction_node<EOL><DEDENT>layer_dicts.append(new_dict)<EOL><DEDENT>else:<EOL><INDENT>curr_dict = layer_dicts[-i]<EOL>for index in gate_span:<EOL><INDENT>curr_dict[index] = instruction_node<EOL><DEDENT><DEDENT>break<EOL><DEDENT><DEDENT>if not added:<EOL><INDENT>for index in gate_span:<EOL><INDENT>layer_dicts[<NUM_LIT:0>][index] = instruction_node<EOL><DEDENT><DEDENT><DEDENT><DEDENT>layer_dicts.reverse()<EOL>ops = [list(layer.values()) for layer in layer_dicts]<EOL><DEDENT>if reverse_bits:<EOL><INDENT>qregs.reverse()<EOL>cregs.reverse()<EOL><DEDENT>return qregs, cregs, ops<EOL>

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


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

Get the list of qubits drawing this gate would cover


it = itertools.groupby(bit_labels, operator.itemgetter(<NUM_LIT:0>))<EOL>for register_name, sub_it in it:<EOL><INDENT>yield register_name, max(ind[<NUM_LIT:1>] for ind in sub_it) + <NUM_LIT:1><EOL><DEDENT>

Get the number and size of unique registers from bit_labels list.

    Args:
        bit_labels (list): this list is of the form::

            [['reg1', 0], ['reg1', 1], ['reg2', 0]]

            which indicates a register named "reg1" of size 2
            and a register named "reg2" of size 1. This is the
            format of classic and quantum bit labels in qobj
            header.

    Yields:
        tuple: iterator of register_name:size pairs.


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

Truncate long floats

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


def __init__(self, qregs, cregs, ops, scale, style=None,<EOL>plot_barriers=True, reverse_bits=False):

<EOL>self._style = _qcstyle.QCStyle()<EOL>if style:<EOL><INDENT>if isinstance(style, dict):<EOL><INDENT>self._style.set_style(style)<EOL><DEDENT>elif isinstance(style, str):<EOL><INDENT>with open(style, '<STR_LIT:r>') as infile:<EOL><INDENT>dic = json.load(infile)<EOL><DEDENT>self._style.set_style(dic)<EOL><DEDENT><DEDENT>self.ops = ops<EOL>self.scale = scale<EOL>self.qregs = {}<EOL>self.cregs = {}<EOL>self.ordered_regs = []<EOL>self.img_regs = {}<EOL>self._latex = []<EOL>self.img_depth = <NUM_LIT:0><EOL>self.img_width = <NUM_LIT:0><EOL>self.sum_column_widths = <NUM_LIT:0><EOL>self.sum_row_heights = <NUM_LIT:0><EOL>self.column_separation = <NUM_LIT:0.5><EOL>self.row_separation = <NUM_LIT:0.0><EOL>self.has_box = False<EOL>self.has_target = False<EOL>self.reverse_bits = reverse_bits<EOL>self.plot_barriers = plot_barriers<EOL>self.qregs = collections.OrderedDict(_get_register_specs(qregs))<EOL>self.qubit_list = qregs<EOL>self.ordered_regs = qregs + cregs<EOL>self.cregs = collections.OrderedDict(_get_register_specs(cregs))<EOL>self.clbit_list = cregs<EOL>self.img_regs = {bit: ind for ind, bit in<EOL>enumerate(self.ordered_regs)}<EOL>self.img_width = len(self.img_regs)<EOL>self.wire_type = {}<EOL>for key, value in self.ordered_regs:<EOL><INDENT>self.wire_type[(key, value)] = key in self.cregs.keys()<EOL><DEDENT>

Args:
    qregs (list): A list of tuples for the quantum registers
    cregs (list): A list of tuples for the classical registers
    ops (list): A list of dicts where each entry is a operation from
        the circuit.
    scale (float): image scaling
    style (dict or str): dictionary of style or file name of style file
    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.


self._initialize_latex_array(aliases)<EOL>self._build_latex_array(aliases)<EOL>header_1 = r"""<STR_LIT>"""% instead and customize the height and width (in cm) to fit.<EOL>images may run out of memory quickly.<EOL><INDENT>this use the LuaLaTeX compiler, which dynamically<EOL><DEDENT>tes memory.<EOL>age[braket, qm]{qcircuit}<EOL>age{amsmath}<EOL>ile{+sansmathaccent.map}<EOL>ckage[landscape]{geometry}<EOL>t out the above line if using the beamer documentclass.<EOL>ocument}<EOL>quation*}"""<STR_LIT>"""<EOL>rcuit @C=%<NUM_LIT>fem @R=%<NUM_LIT>fem @!R {<EOL>output = io.StringIO()<EOL>output.write(header_1)<EOL>output.write('<STR_LIT>' % (self.img_width, self.img_depth))<EOL>output.write(beamer_line % self._get_beamer_page())<EOL>output.write(header_2)<EOL>output.write(qcircuit_line %<EOL><INDENT>(self.column_separation, self.row_separation))<EOL>for i in range(self.img_width):<EOL>output.write("<STR_LIT>")<EOL>for j in range(self.img_depth + <NUM_LIT:1>):<EOL>cell_str = self._latex[i][j]<EOL>if '<STR_LIT>' in cell_str:<EOL>output.write(cell_str)<EOL>else:<EOL>cell_str = re.sub(r'<STR_LIT>',<EOL><INDENT>_truncate_float,<EOL>cell_str)<EOL>output.write(cell_str)<EOL>if j != self.img_depth:<EOL>output.write("<STR_LIT>")<EOL>else:<EOL>output.write(r'<STR_LIT:\\>' + '<STR_LIT:\n>')<EOL>output.write('<STR_LIT>')<EOL>output.write('<STR_LIT>')<EOL>output.write('<STR_LIT>')<EOL>contents = output.getvalue()<EOL>output.close()<EOL>return contents<EOL>

Return LaTeX string representation of circuit.

        This method uses the LaTeX Qconfig package to create a graphical
        representation of the circuit.

        Returns:
            string: for writing to a LaTeX file.


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

Get depth information for the circuit.

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


<EOL>PIL_limit = <NUM_LIT><EOL>beamer_limit = <NUM_LIT><EOL>aspect_ratio = self.sum_row_heights / self.sum_column_widths<EOL>margin_factor = <NUM_LIT><EOL>height = min(self.sum_row_heights * margin_factor, beamer_limit)<EOL>width = min(self.sum_column_widths * margin_factor, beamer_limit)<EOL>if height * width > PIL_limit:<EOL><INDENT>height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)<EOL>width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)<EOL><DEDENT>height = max(height, <NUM_LIT:10>)<EOL>width = max(width, <NUM_LIT:10>)<EOL>return (height, width, self.scale)<EOL>

Get height, width & scale attributes for the beamer page.

        Returns:
            tuple: (height, width, scale) desirable page attributes


columns = <NUM_LIT:1><EOL>if aliases:<EOL><INDENT>qregdata = {}<EOL>for q in aliases.values():<EOL><INDENT>if q[<NUM_LIT:0>] not in qregdata:<EOL><INDENT>qregdata[q[<NUM_LIT:0>]] = q[<NUM_LIT:1>] + <NUM_LIT:1><EOL><DEDENT>elif qregdata[q[<NUM_LIT:0>]] < q[<NUM_LIT:1>] + <NUM_LIT:1>:<EOL><INDENT>qregdata[q[<NUM_LIT:0>]] = q[<NUM_LIT:1>] + <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>qregdata = self.qregs<EOL><DEDENT>for column, layer in enumerate(self.ops, <NUM_LIT:1>):<EOL><INDENT>for op in layer:<EOL><INDENT>if op.condition:<EOL><INDENT>mask = self._get_mask(op.condition[<NUM_LIT:0>])<EOL>cl_reg = self.clbit_list[self._ffs(mask)]<EOL>if_reg = cl_reg[<NUM_LIT:0>]<EOL>pos_2 = self.img_regs[cl_reg]<EOL>if_value = format(op.condition[<NUM_LIT:1>],<EOL>'<STR_LIT:b>').zfill(self.cregs[if_reg])[::-<NUM_LIT:1>]<EOL><DEDENT>if op.name not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>nm = op.name<EOL>qarglist = op.qargs<EOL>if aliases is not None:<EOL><INDENT>qarglist = map(lambda x: aliases[x], qarglist)<EOL><DEDENT>if len(qarglist) == <NUM_LIT:1>:<EOL><INDENT>pos_1 = self.img_regs[(qarglist[<NUM_LIT:0>][<NUM_LIT:0>],<EOL>qarglist[<NUM_LIT:0>][<NUM_LIT:1>])]<EOL>if op.condition:<EOL><INDENT>mask = self._get_mask(op.condition[<NUM_LIT:0>])<EOL>cl_reg = self.clbit_list[self._ffs(mask)]<EOL>if_reg = cl_reg[<NUM_LIT:0>]<EOL>pos_2 = self.img_regs[cl_reg]<EOL>if nm == "<STR_LIT:x>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:y>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:z>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:h>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:s>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:t>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>], op.op.params[<NUM_LIT:1>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = ("<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>],<EOL>op.op.params[<NUM_LIT:1>],<EOL>op.op.params[<NUM_LIT:2>]))<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>self._latex[pos_1][columns] = "<STR_LIT>" % nm<EOL><DEDENT>gap = pos_2 - pos_1<EOL>for i in range(self.cregs[if_reg]):<EOL><INDENT>if if_value[i] == '<STR_LIT:1>':<EOL><INDENT>self._latex[pos_2 + i][column] ="<STR_LIT>" + str(gap) + "<STR_LIT:]>"<EOL>gap = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self._latex[pos_2 + i][column] ="<STR_LIT>" + str(gap) + "<STR_LIT:]>"<EOL>gap = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if nm == "<STR_LIT:x>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:y>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:z>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:h>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:s>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT:t>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>], op.op.params[<NUM_LIT:1>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = ("<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>],<EOL>op.op.params[<NUM_LIT:1>],<EOL>op.op.params[<NUM_LIT:2>]))<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self._latex[pos_1][columns] = "<STR_LIT>" % nm<EOL><DEDENT><DEDENT><DEDENT>elif len(qarglist) == <NUM_LIT:2>:<EOL><INDENT>pos_1 = self.img_regs[(qarglist[<NUM_LIT:0>][<NUM_LIT:0>], qarglist[<NUM_LIT:0>][<NUM_LIT:1>])]<EOL>pos_2 = self.img_regs[(qarglist[<NUM_LIT:1>][<NUM_LIT:0>], qarglist[<NUM_LIT:1>][<NUM_LIT:1>])]<EOL>if op.condition:<EOL><INDENT>pos_3 = self.img_regs[(if_reg, <NUM_LIT:0>)]<EOL>temp = [pos_1, pos_2, pos_3]<EOL>temp.sort(key=int)<EOL>bottom = temp[<NUM_LIT:1>]<EOL>gap = pos_3 - bottom<EOL>for i in range(self.cregs[if_reg]):<EOL><INDENT>if if_value[i] == '<STR_LIT:1>':<EOL><INDENT>self._latex[pos_3 + i][column] ="<STR_LIT>" + str(gap) + "<STR_LIT:]>"<EOL>gap = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self._latex[pos_3 + i][column] ="<STR_LIT>" + str(gap) + "<STR_LIT:]>"<EOL>gap = <NUM_LIT:1><EOL><DEDENT><DEDENT>if nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL>self._latex[pos_2][column] ="<STR_LIT>" + str(pos_1 - pos_2) + "<STR_LIT:]>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] ="<STR_LIT>" % (op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column - <NUM_LIT:1>] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column - <NUM_LIT:1>] = "<STR_LIT>"<EOL>self._latex[min(pos_1, pos_2)][column] ="<STR_LIT>" % (op.op.params[<NUM_LIT:0>])<EOL>self._latex[max(pos_1, pos_2)][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] ="<STR_LIT>" % (op.op.params[<NUM_LIT:0>],<EOL>op.op.params[<NUM_LIT:1>],<EOL>op.op.params[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>temp = [pos_1, pos_2]<EOL>temp.sort(key=int)<EOL>if nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL>self._latex[pos_2][column] ="<STR_LIT>" + str(pos_1 - pos_2) + "<STR_LIT:]>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] ="<STR_LIT>" % (op.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column - <NUM_LIT:1>] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column - <NUM_LIT:1>] = "<STR_LIT>"<EOL>self._latex[min(pos_1, pos_2)][column] ="<STR_LIT>" % (op.op.params[<NUM_LIT:0>])<EOL>self._latex[max(pos_1, pos_2)][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = ("<STR_LIT>" % (<EOL>op.op.params[<NUM_LIT:0>],<EOL>op.op.params[<NUM_LIT:1>],<EOL>op.op.params[<NUM_LIT:2>]))<EOL><DEDENT>else:<EOL><INDENT>start_pos = min([pos_1, pos_2])<EOL>stop_pos = max([pos_1, pos_2])<EOL>if stop_pos - start_pos >= <NUM_LIT:2>:<EOL><INDENT>delta = stop_pos - start_pos<EOL>self._latex[start_pos][columns] = (<EOL>"<STR_LIT>" % (delta, nm))<EOL>for i_pos in range(start_pos + <NUM_LIT:1>, stop_pos + <NUM_LIT:1>):<EOL><INDENT>self._latex[i_pos][columns] = "<STR_LIT>" % nm<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._latex[start_pos][columns] = (<EOL>"<STR_LIT>" % nm)<EOL>self._latex[stop_pos][columns] = "<STR_LIT>" % nm<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif len(qarglist) == <NUM_LIT:3>:<EOL><INDENT>pos_1 = self.img_regs[(qarglist[<NUM_LIT:0>][<NUM_LIT:0>], qarglist[<NUM_LIT:0>][<NUM_LIT:1>])]<EOL>pos_2 = self.img_regs[(qarglist[<NUM_LIT:1>][<NUM_LIT:0>], qarglist[<NUM_LIT:1>][<NUM_LIT:1>])]<EOL>pos_3 = self.img_regs[(qarglist[<NUM_LIT:2>][<NUM_LIT:0>], qarglist[<NUM_LIT:2>][<NUM_LIT:1>])]<EOL>if op.condition:<EOL><INDENT>pos_4 = self.img_regs[(if_reg, <NUM_LIT:0>)]<EOL>temp = [pos_1, pos_2, pos_3, pos_4]<EOL>temp.sort(key=int)<EOL>bottom = temp[<NUM_LIT:2>]<EOL>prev_column = [x[column - <NUM_LIT:1>] for x in self._latex]<EOL>for item, prev_entry in enumerate(prev_column):<EOL><INDENT>if '<STR_LIT>' in prev_entry:<EOL><INDENT>span = re.search('<STR_LIT>', prev_entry)<EOL>if span and any(i in temp for i in range(<EOL>item, int(span.group(<NUM_LIT:1>)))):<EOL><INDENT>self._latex[item][column - <NUM_LIT:1>] =prev_entry.replace(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>gap = pos_4 - bottom<EOL>for i in range(self.cregs[if_reg]):<EOL><INDENT>if if_value[i] == '<STR_LIT:1>':<EOL><INDENT>self._latex[pos_4 + i][column] ="<STR_LIT>" + str(gap) + "<STR_LIT:]>"<EOL>gap = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self._latex[pos_4 + i][column] ="<STR_LIT>" + str(gap) + "<STR_LIT:]>"<EOL>gap = <NUM_LIT:1><EOL><DEDENT><DEDENT>if nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>" + str(<EOL>pos_3 - pos_2) + "<STR_LIT:}>"<EOL>self._latex[pos_3][column] = "<STR_LIT>"<EOL><DEDENT>if nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL>self._latex[pos_3][column] ="<STR_LIT>" + str(pos_2 - pos_3) + "<STR_LIT:]>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>temp = [pos_1, pos_2, pos_3]<EOL>temp.sort(key=int)<EOL>prev_column = [x[column - <NUM_LIT:1>] for x in self._latex]<EOL>for item, prev_entry in enumerate(prev_column):<EOL><INDENT>if '<STR_LIT>' in prev_entry:<EOL><INDENT>span = re.search('<STR_LIT>', prev_entry)<EOL>if span and any(i in temp for i in range(<EOL>item, int(span.group(<NUM_LIT:1>)))):<EOL><INDENT>self._latex[item][column - <NUM_LIT:1>] =prev_entry.replace(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>if nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>" + str(<EOL>pos_3 - pos_2) + "<STR_LIT:}>"<EOL>self._latex[pos_3][column] = "<STR_LIT>"<EOL><DEDENT>elif nm == "<STR_LIT>":<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>" + str(<EOL>pos_2 - pos_1) + "<STR_LIT:}>"<EOL>self._latex[pos_2][column] = "<STR_LIT>"<EOL>self._latex[pos_3][column] ="<STR_LIT>" + str(pos_2 - pos_3) + "<STR_LIT:]>"<EOL><DEDENT>else:<EOL><INDENT>start_pos = min([pos_1, pos_2, pos_3])<EOL>stop_pos = max([pos_1, pos_2, pos_3])<EOL>if stop_pos - start_pos >= <NUM_LIT:3>:<EOL><INDENT>delta = stop_pos - start_pos<EOL>self._latex[start_pos][columns] = (<EOL>"<STR_LIT>" % (delta, nm))<EOL>for i_pos in range(start_pos + <NUM_LIT:1>, stop_pos + <NUM_LIT:1>):<EOL><INDENT>self._latex[i_pos][columns] = "<STR_LIT>" % nm<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._latex[pos_1][columns] = (<EOL>"<STR_LIT>" % nm)<EOL>self._latex[pos_2][columns] = "<STR_LIT>" % nm<EOL>self._latex[pos_3][columns] = "<STR_LIT>" % nm<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif len(qarglist) > <NUM_LIT:3>:<EOL><INDENT>nbits = len(qarglist)<EOL>pos_array = [self.img_regs[(qarglist[<NUM_LIT:0>][<NUM_LIT:0>],<EOL>qarglist[<NUM_LIT:0>][<NUM_LIT:1>])]]<EOL>for i in range(<NUM_LIT:1>, nbits):<EOL><INDENT>pos_array.append(self.img_regs[(qarglist[i][<NUM_LIT:0>],<EOL>qarglist[i][<NUM_LIT:1>])])<EOL><DEDENT>pos_start = min(pos_array)<EOL>pos_stop = max(pos_array)<EOL>delta = pos_stop - pos_start<EOL>self._latex[pos_start][columns] = (<EOL>"<STR_LIT>" % (nbits - <NUM_LIT:1>, nm))<EOL>for pos in range(pos_start + <NUM_LIT:1>, pos_stop + <NUM_LIT:1>):<EOL><INDENT>self._latex[pos][columns] = "<STR_LIT>" % nm<EOL><DEDENT><DEDENT><DEDENT>elif op.name == "<STR_LIT>":<EOL><INDENT>if (len(op.cargs) != <NUM_LIT:1><EOL>or len(op.qargs) != <NUM_LIT:1><EOL>or op.op.params):<EOL><INDENT>raise exceptions.VisualizationError("<STR_LIT>")<EOL><DEDENT>if op.condition:<EOL><INDENT>raise exceptions.VisualizationError(<EOL>"<STR_LIT>")<EOL><DEDENT>qname, qindex = op.qargs[<NUM_LIT:0>]<EOL>cname, cindex = op.cargs[<NUM_LIT:0>]<EOL>if aliases:<EOL><INDENT>newq = aliases[(qname, qindex)]<EOL>qname = newq[<NUM_LIT:0>]<EOL>qindex = newq[<NUM_LIT:1>]<EOL><DEDENT>pos_1 = self.img_regs[(qname, qindex)]<EOL>pos_2 = self.img_regs[(cname, cindex)]<EOL>try:<EOL><INDENT>self._latex[pos_1][column] = "<STR_LIT>"<EOL>prev_column = [x[column - <NUM_LIT:1>] for x in self._latex]<EOL>for item, prev_entry in enumerate(prev_column):<EOL><INDENT>if '<STR_LIT>' in prev_entry:<EOL><INDENT>span = re.search('<STR_LIT>', prev_entry)<EOL>if span and (<EOL>item + int(span.group(<NUM_LIT:1>))) - pos_1 >= <NUM_LIT:0>:<EOL><INDENT>self._latex[item][column - <NUM_LIT:1>] =prev_entry.replace(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>self._latex[pos_2][column] ="<STR_LIT>" + str(pos_2 - pos_1) + "<STR_LIT:]>"<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise exceptions.VisualizationError(<EOL>'<STR_LIT>' % str(e))<EOL><DEDENT><DEDENT>elif op.name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>if self.plot_barriers:<EOL><INDENT>qarglist = op.qargs<EOL>indexes = [self._get_qubit_index(x) for x in qarglist]<EOL>start_bit = self.qubit_list[min(indexes)]<EOL>if aliases is not None:<EOL><INDENT>qarglist = map(lambda x: aliases[x], qarglist)<EOL><DEDENT>start = self.img_regs[start_bit]<EOL>span = len(op.qargs) - <NUM_LIT:1><EOL>self._latex[start][column] = "<STR_LIT>" + str(<EOL>span) + "<STR_LIT:}>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.VisualizationError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

Returns an array of strings containing \\LaTeX for this circuit.

        If aliases is not None, aliases contains a dict mapping
        the current qubits in the circuit to new qubit names.
        We will deduce the register names and sizes from aliases.


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

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


origin = (mask & (-mask)).bit_length()<EOL>return origin - <NUM_LIT:1><EOL>

Find index of first set bit.

        Args:
            mask (int): integer to search
        Returns:
            int: index of the first set bit.


def dag_drawer(dag, scale=<NUM_LIT>, filename=None, style='<STR_LIT>'):

try:<EOL><INDENT>import nxpd<EOL>import pydot  <EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>G = dag.to_networkx()<EOL>G.graph['<STR_LIT>'] = <NUM_LIT:100> * scale<EOL>if style == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>elif style == '<STR_LIT>':<EOL><INDENT>for node in G.nodes:<EOL><INDENT>n = G.nodes[node]<EOL>n['<STR_LIT:label>'] = node.name<EOL>if node.type == '<STR_LIT>':<EOL><INDENT>n['<STR_LIT>'] = '<STR_LIT>'<EOL>n['<STR_LIT>'] = '<STR_LIT>'<EOL>n['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if node.type == '<STR_LIT>':<EOL><INDENT>n['<STR_LIT>'] = '<STR_LIT>'<EOL>n['<STR_LIT>'] = '<STR_LIT>'<EOL>n['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if node.type == '<STR_LIT>':<EOL><INDENT>n['<STR_LIT>'] = '<STR_LIT>'<EOL>n['<STR_LIT>'] = '<STR_LIT>'<EOL>n['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT><DEDENT>for e in G.edges(data=True):<EOL><INDENT>e[<NUM_LIT:2>]['<STR_LIT:label>'] = e[<NUM_LIT:2>]['<STR_LIT:name>']<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise VisualizationError("<STR_LIT>")<EOL><DEDENT>if filename:<EOL><INDENT>show = False<EOL><DEDENT>elif ('<STR_LIT>' in sys.modules) and ('<STR_LIT>' not in sys.modules):<EOL><INDENT>show = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>show = True<EOL><DEDENT>return nxpd.draw(G, filename=filename, show=show)<EOL>

Plot the directed acyclic graph (dag) to represent operation dependencies
    in a quantum circuit.

    Note this function leverages
    `pydot <https://github.com/erocarrera/pydot>`_ (via
    `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which
    means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
    system is required for this to work.

    Args:
        dag (DAGCircuit): The dag to draw.
        scale (float): scaling factor
        filename (str): file path to save image to (format inferred from name)
        style (str): 'plain': B&W graph
                     'color' (default): color input/output/op nodes

    Returns:
        Ipython.display.Image: if in Jupyter notebook and not saving to file,
            otherwise None.

    Raises:
        VisualizationError: when style is not recognized.
        ImportError: when nxpd or pydot not installed.


<EOL>self.graph = nx.DiGraph()<EOL>self._dist_matrix = None<EOL>self._qubit_list = None<EOL>if couplinglist is not None:<EOL><INDENT>for source, target in couplinglist:<EOL><INDENT>self.add_edge(source, target)<EOL><DEDENT><DEDENT>

Create coupling graph. By default, the generated coupling has no nodes.

Args:
    couplinglist (list or None): An initial coupling graph, specified as
        an adjacency list containing couplings, e.g. [[0,1], [0,2], [1,2]].


return len(self.graph.nodes)<EOL>

Return the number of physical qubits in this graph.


return [edge for edge in self.graph.edges()]<EOL>

Gets the list of edges in the coupling graph.

Returns:
    Tuple(int,int): Each edge is a pair of physical qubits.


if not isinstance(physical_qubit, int):<EOL><INDENT>raise CouplingError("<STR_LIT>")<EOL><DEDENT>if physical_qubit in self.physical_qubits:<EOL><INDENT>raise CouplingError(<EOL>"<STR_LIT>" % physical_qubit)<EOL><DEDENT>self.graph.add_node(physical_qubit)<EOL>self._dist_matrix = None  <EOL>self._qubit_list = None<EOL>

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 src not in self.physical_qubits:<EOL><INDENT>self.add_physical_qubit(src)<EOL><DEDENT>if dst not in self.physical_qubits:<EOL><INDENT>self.add_physical_qubit(dst)<EOL><DEDENT>self.graph.add_edge(src, dst)<EOL>self._dist_matrix = None<EOL>

Add directed edge to coupling graph.

src (int): source physical qubit
dst (int): destination physical qubit


subcoupling = CouplingMap()<EOL>subcoupling.graph = self.graph.subgraph(nodelist)<EOL>for node in nodelist:<EOL><INDENT>if node not in subcoupling.physical_qubits:<EOL><INDENT>subcoupling.add_physical_qubit(node)<EOL><DEDENT><DEDENT>return subcoupling<EOL>

Return a CouplingMap object for a subgraph of self.

        nodelist (list): list of integer node labels


if self._qubit_list is None:<EOL><INDENT>self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes])<EOL><DEDENT>return self._qubit_list<EOL>

Returns a sorted list of physical_qubits


try:<EOL><INDENT>return nx.is_weakly_connected(self.graph)<EOL><DEDENT>except nx.exception.NetworkXException:<EOL><INDENT>return False<EOL><DEDENT>

Test if the graph is connected.

Return True if connected, False otherwise


if not self.is_connected():<EOL><INDENT>raise CouplingError("<STR_LIT>")<EOL><DEDENT>lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True))<EOL>lengths = dict(lengths)<EOL>size = len(lengths)<EOL>cmap = np.zeros((size, size))<EOL>for idx in range(size):<EOL><INDENT>cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter(<EOL>lengths[idx].values(), dtype=int)<EOL><DEDENT>self._dist_matrix = cmap<EOL>

Compute the full distance matrix on pairs of nodes.

        The distance map self._dist_matrix is computed from the graph using
        all_pairs_shortest_path_length.


def distance(self, physical_qubit1, physical_qubit2):

if physical_qubit1 not in self.physical_qubits:<EOL><INDENT>raise CouplingError("<STR_LIT>" % (physical_qubit1,))<EOL><DEDENT>if physical_qubit2 not in self.physical_qubits:<EOL><INDENT>raise CouplingError("<STR_LIT>" % (physical_qubit2,))<EOL><DEDENT>if self._dist_matrix is None:<EOL><INDENT>self._compute_distance_matrix()<EOL><DEDENT>return self._dist_matrix[physical_qubit1, physical_qubit2]<EOL>

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


string = "<STR_LIT>"<EOL>if self.get_edges():<EOL><INDENT>string += "<STR_LIT:[>"<EOL>string += "<STR_LIT:U+002CU+0020>".join(["<STR_LIT>" % (src, dst) for (src, dst) in self.get_edges()])<EOL>string += "<STR_LIT:]>"<EOL><DEDENT>return string<EOL>

Return a string representation of the coupling graph.


if name in object.__getattribute__(self, '<STR_LIT>'):<EOL><INDENT>raise TranspilerAccessError("<STR_LIT>" %<EOL>(type(object.__getattribute__(self, '<STR_LIT>')), name))<EOL><DEDENT>

Checks if the attribute name is in the list of attributes to protect. If so, raises
TranspilerAccessError.

Args:
    name (string): the attribute name to check

Raises:
    TranspilerAccessError: when name is the list of attributes to protect.


<EOL>self.working_list = []<EOL>self.property_set = PropertySet()<EOL>self.fenced_property_set = FencedPropertySet(self.property_set)<EOL>self.valid_passes = set()<EOL>self.passmanager_options = {'<STR_LIT>': ignore_requires,<EOL>'<STR_LIT>': ignore_preserves,<EOL>'<STR_LIT>': max_iteration}<EOL>if passes is not None:<EOL><INDENT>self.append(passes)<EOL><DEDENT>

Initialize an empty PassManager object (with no passes scheduled).

Args:
    passes (list[BasePass] or BasePass): pass(es) to be added to schedule. The default is
        None.
    ignore_requires (bool): The schedule ignores the requires field in the passes. The
        default setting in the pass is False.
    ignore_preserves (bool): The schedule ignores the preserves field in the passes. The
        default setting in the pass is False.
    max_iteration (int): The schedule looping iterates until the condition is met or until
        max_iteration is reached.


default = {'<STR_LIT>': False,  <EOL>'<STR_LIT>': False,  <EOL>'<STR_LIT>': <NUM_LIT:1000>}  <EOL>passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None}<EOL>passset_level = {k: v for k, v in passset_options.items() if v is not None}<EOL>return {**default, **passmanager_level, **passset_level}<EOL>

Set the options of each passset, based on precedence rules:
        passset options (set via ``PassManager.append()``) override
        passmanager options (set via ``PassManager.__init__()``), which override Default.
        .


def append(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None,<EOL>**flow_controller_conditions):

passset_options = {'<STR_LIT>': ignore_requires,<EOL>'<STR_LIT>': ignore_preserves,<EOL>'<STR_LIT>': max_iteration}<EOL>options = self._join_options(passset_options)<EOL>if isinstance(passes, BasePass):<EOL><INDENT>passes = [passes]<EOL><DEDENT>for pass_ in passes:<EOL><INDENT>if not isinstance(pass_, BasePass):<EOL><INDENT>raise TranspilerError('<STR_LIT>' % pass_.__class__)<EOL><DEDENT><DEDENT>for name, param in flow_controller_conditions.items():<EOL><INDENT>if callable(param):<EOL><INDENT>flow_controller_conditions[name] = partial(param, self.fenced_property_set)<EOL><DEDENT>else:<EOL><INDENT>raise TranspilerError('<STR_LIT>' % name)<EOL><DEDENT><DEDENT>self.working_list.append(<EOL>FlowController.controller_factory(passes, options, **flow_controller_conditions))<EOL>

Args:
    passes (list[BasePass] or BasePass): pass(es) to be added to schedule
    ignore_preserves (bool): ignore the preserves claim of passes. Default: False
    ignore_requires (bool): ignore the requires need of passes. Default: False
    max_iteration (int): max number of iterations of passes. Default: 1000
    flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of
    control flow plugins. Default:

        * do_while (callable property_set -> boolean): The passes repeat until the
          callable returns False.
          Default: `lambda x: False # i.e. passes run once`

        * condition (callable property_set -> boolean): The passes run only if the
          callable returns True.
          Default: `lambda x: True # i.e. passes run`

Raises:
    TranspilerError: if a pass in passes is not a proper pass.


name = circuit.name<EOL>dag = circuit_to_dag(circuit)<EOL>del circuit<EOL>for passset in self.working_list:<EOL><INDENT>for pass_ in passset:<EOL><INDENT>dag = self._do_pass(pass_, dag, passset.options)<EOL><DEDENT><DEDENT>circuit = dag_to_circuit(dag)<EOL>circuit.name = name<EOL>return circuit<EOL>

Run all the passes on a QuantumCircuit

        Args:
            circuit (QuantumCircuit): circuit to transform via all the registered passes

        Returns:
            QuantumCircuit: Transformed circuit.


def _do_pass(self, pass_, dag, options):

<EOL>if not options["<STR_LIT>"]:<EOL><INDENT>for required_pass in pass_.requires:<EOL><INDENT>dag = self._do_pass(required_pass, dag, options)<EOL><DEDENT><DEDENT>if pass_ not in self.valid_passes:<EOL><INDENT>if pass_.is_transformation_pass:<EOL><INDENT>pass_.property_set = self.fenced_property_set<EOL>new_dag = pass_.run(dag)<EOL>if not isinstance(new_dag, DAGCircuit):<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>" % (type(pass_).__name__,<EOL>type(new_dag)))<EOL><DEDENT>dag = new_dag<EOL><DEDENT>elif pass_.is_analysis_pass:<EOL><INDENT>pass_.property_set = self.property_set<EOL>pass_.run(FencedDAGCircuit(dag))<EOL><DEDENT>else:<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>self._update_valid_passes(pass_, options['<STR_LIT>'])<EOL><DEDENT>return dag<EOL>

Do a pass and its "requires".

        Args:
            pass_ (BasePass): Pass to do.
            dag (DAGCircuit): The dag on which the pass is ran.
            options (dict): PassManager options.
        Returns:
            DAGCircuit: The transformed dag in case of a transformation pass.
            The same input dag in case of an analysis pass.
        Raises:
            TranspilerError: If the pass is not a proper pass instance.


ret = []<EOL>for pass_ in self.working_list:<EOL><INDENT>ret.append(pass_.dump_passes())<EOL><DEDENT>return ret<EOL>

Returns a list structure of the appended passes and its options.

Returns (list): The appended passes.


ret = {'<STR_LIT>': self.options, '<STR_LIT>': [], '<STR_LIT:type>': type(self)}<EOL>for pass_ in self._passes:<EOL><INDENT>if isinstance(pass_, FlowController):<EOL><INDENT>ret['<STR_LIT>'].append(pass_.dump_passes())<EOL><DEDENT>else:<EOL><INDENT>ret['<STR_LIT>'].append(pass_)<EOL><DEDENT><DEDENT>return ret<EOL>

Fetches the passes added to this flow controller.

Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)}


@classmethod<EOL><INDENT>def add_flow_controller(cls, name, controller):<DEDENT>

cls.registered_controllers[name] = controller<EOL>

Adds a flow controller.
Args:
    name (string): Name of the controller to add.
    controller (type(FlowController)): The class implementing a flow controller.


if name not in cls.registered_controllers:<EOL><INDENT>raise KeyError("<STR_LIT>" % name)<EOL><DEDENT>del cls.registered_controllers[name]<EOL>

Removes a flow controller.
Args:
    name (string): Name of the controller to remove.
Raises:
    KeyError: If the controller to remove was not registered.


@classmethod<EOL><INDENT>def controller_factory(cls, passes, options, **partial_controller):<DEDENT>

if None in partial_controller.values():<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>if partial_controller:<EOL><INDENT>for registered_controller in cls.registered_controllers.keys():<EOL><INDENT>if registered_controller in partial_controller:<EOL><INDENT>return cls.registered_controllers[registered_controller](passes, options,<EOL>**partial_controller)<EOL><DEDENT><DEDENT>raise TranspilerError("<STR_LIT>" % partial_controller)<EOL><DEDENT>else:<EOL><INDENT>return FlowControllerLinear(passes, options)<EOL><DEDENT>

Constructs a flow controller based on the partially evaluated controller arguments.

Args:
    passes (list[BasePass]): passes to add to the flow controller.
    options (dict): PassManager options.
    **partial_controller (dict): Partially evaluated controller arguments in the form
        `{name:partial}`

Raises:
    TranspilerError: When partial_controller is not well-formed.

Returns:
    FlowController: A FlowController instance.


def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):

pass_manager = PassManager()<EOL>pass_manager.property_set['<STR_LIT>'] = initial_layout<EOL>pass_manager.append(Unroller(basis_gates))<EOL>pass_manager.append(TrivialLayout(coupling_map),<EOL>condition=lambda property_set: not property_set['<STR_LIT>'])<EOL>pass_manager.append(CheckMap(coupling_map))<EOL>pass_manager.append(DenseLayout(coupling_map),<EOL>condition=lambda property_set: not property_set['<STR_LIT>'])<EOL>pass_manager.append(FullAncillaAllocation(coupling_map))<EOL>pass_manager.append(EnlargeWithAncilla())<EOL>pass_manager.append(Unroll3qOrMore())<EOL>pass_manager.append(LegacySwap(coupling_map, trials=<NUM_LIT:20>, seed=seed_transpiler))<EOL>pass_manager.append(Decompose(SwapGate))<EOL>pass_manager.append(CXDirection(coupling_map))<EOL>pass_manager.append(Unroller(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:id>', '<STR_LIT>']))<EOL>simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()]<EOL>pass_manager.append(simplification_passes + [Depth(), FixedPoint('<STR_LIT>')],<EOL>do_while=lambda property_set: not property_set['<STR_LIT>'])<EOL>return pass_manager<EOL>

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()<EOL>pass_manager.append(Unroller(basis_gates))<EOL>pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('<STR_LIT>')],<EOL>do_while=lambda property_set: not property_set['<STR_LIT>'])<EOL>return pass_manager<EOL>

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.


def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,<EOL>initial_layout=None, seed_mapper=None, pass_manager=None):

transpile one or more circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        basis_gates (list[str]): list of basis gate names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits. The final
            layout is not guaranteed to be the same, as the transpiler may permute
            qubits through swaps or other means.

        seed_mapper (int): random seed for the swap_mapper
        pass_manager (PassManager): a pass_manager for the transpiler stages

    Returns:
        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes


def transpile_dag(dag, basis_gates=None, coupling_map=None,<EOL>initial_layout=None, seed_mapper=None, pass_manager=None):

warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>if basis_gates is None:<EOL><INDENT>basis_gates = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:id>']<EOL><DEDENT>if pass_manager is None:<EOL><INDENT>if coupling_map:<EOL><INDENT>pass_manager = default_pass_manager(basis_gates,<EOL>CouplingMap(coupling_map),<EOL>initial_layout,<EOL>seed_transpiler=seed_mapper)<EOL><DEDENT>else:<EOL><INDENT>pass_manager = default_pass_manager_simulator(basis_gates)<EOL><DEDENT><DEDENT>name = dag.name<EOL>circuit = dag_to_circuit(dag)<EOL>circuit = pass_manager.run(circuit)<EOL>dag = circuit_to_dag(circuit)<EOL>dag.name = name<EOL>return dag<EOL>

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


return self.__class__.__name__<EOL>


raise NotImplementedError<EOL>

Run a pass on the DAGCircuit. This is implemented by the pass developer.
Args:
    dag (DAGCircuit): the dag on which the pass is run.
Raises:
    NotImplementedError: when this is left unimplemented for a pass.


return isinstance(self, TransformationPass)<EOL>

If the pass is a TransformationPass, that means that the pass can manipulate the DAG,
        but cannot modify the property set (but it can be read).


return isinstance(self, AnalysisPass)<EOL>

If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write
        the results of that analysis in the property set. Modifications on the DAG are not allowed
        by this kind of pass.


self._p2v = {}<EOL>self._v2p = {}<EOL>if input_dict is not None:<EOL><INDENT>if not isinstance(input_dict, dict):<EOL><INDENT>raise LayoutError("<STR_LIT>")<EOL><DEDENT>self.from_dict(input_dict)<EOL><DEDENT>

construct a Layout from a bijective dictionary, mapping
        virtual qubits to physical qubits


str_list = []<EOL>for key, val in self._p2v.items():<EOL><INDENT>str_list.append("<STR_LIT>".format(k=key, v=val))<EOL><DEDENT>if str_list:<EOL><INDENT>str_list[-<NUM_LIT:1>] = str_list[-<NUM_LIT:1>][:-<NUM_LIT:1>]<EOL><DEDENT>return "<STR_LIT>" + "<STR_LIT:\n>".join(str_list) + "<STR_LIT>"<EOL>


<EOL>if len(input_dict) >= <NUM_LIT:1>:<EOL><INDENT>key = list(input_dict.keys())[<NUM_LIT:0>]<EOL>value = input_dict[key]<EOL>if (isinstance(key, tuple) and  <EOL>len(key) == <NUM_LIT:2> and<EOL>isinstance(key[<NUM_LIT:0>], str) and<EOL>isinstance(key[<NUM_LIT:1>], int) and<EOL>isinstance(value, tuple) and<EOL>len(value) == <NUM_LIT:2> and<EOL>isinstance(key[<NUM_LIT:0>], str) and<EOL>isinstance(key[<NUM_LIT:1>], int)):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>" % (key + value),<EOL>DeprecationWarning)<EOL>qreg_names = {qubit[<NUM_LIT:0>] for qubit in input_dict.keys()}<EOL>qregs = {}<EOL>for qreg_name in qreg_names:<EOL><INDENT>qregs[qreg_name] = QuantumRegister(<EOL>max([qubit[<NUM_LIT:1>] for qubit in input_dict.keys() if qubit[<NUM_LIT:0>] == qreg_name]) + <NUM_LIT:1>,<EOL>qreg_name)<EOL><DEDENT>new_input_dict = {}<EOL>for key, value in input_dict.items():<EOL><INDENT>new_input_dict[value[<NUM_LIT:1>]] = (qregs[key[<NUM_LIT:0>]], key[<NUM_LIT:1>])<EOL><DEDENT>input_dict = new_input_dict<EOL><DEDENT><DEDENT>for key, value in input_dict.items():<EOL><INDENT>virtual, physical = Layout.order_based_on_type(key, value)<EOL>self._p2v[physical] = virtual<EOL>if virtual is None:<EOL><INDENT>continue<EOL><DEDENT>self._v2p[virtual] = physical<EOL><DEDENT>

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]}


if isinstance(value1, int) and Layout.is_virtual(value2):<EOL><INDENT>physical = value1<EOL>virtual = value2<EOL><DEDENT>elif isinstance(value2, int) and Layout.is_virtual(value1):<EOL><INDENT>physical = value2<EOL>virtual = value1<EOL><DEDENT>else:<EOL><INDENT>raise LayoutError('<STR_LIT>'<EOL>'<STR_LIT>' % (type(value1), type(value2)))<EOL><DEDENT>return virtual, physical<EOL>

decides which one is physical/virtual based on the type. Returns (virtual, physical)


return value is None or isinstance(value, tuple) and len(value) == <NUM_LIT:2> and isinstance(<EOL>value[<NUM_LIT:0>], Register) and isinstance(value[<NUM_LIT:1>], int)<EOL>

Checks if value has the format of a virtual qubit


layout_copy = type(self)()<EOL>layout_copy._p2v = self._p2v.copy()<EOL>layout_copy._v2p = self._v2p.copy()<EOL>return layout_copy<EOL>


def add(self, virtual_bit, physical_bit=None):

if physical_bit is None:<EOL><INDENT>physical_candidate = len(self)<EOL>while physical_candidate in self._p2v:<EOL><INDENT>physical_candidate += <NUM_LIT:1><EOL><DEDENT>physical_bit = physical_candidate<EOL><DEDENT>self[virtual_bit] = physical_bit<EOL>

Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not
defined, `bit` will be mapped to a new physical bit (extending the length of the
layout by one.)
Args:
    virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2).
    physical_bit (int): A physical bit. For example, 3.


for bit in reg:<EOL><INDENT>self.add(bit)<EOL><DEDENT>

Adds at the end physical_qubits that map each bit in reg.
Args:
    reg (Register): A (qu)bit Register. For example, QuantumRegister(3, 'qr').


return {reg for reg, _ in self.get_virtual_bits()}<EOL>

Returns the registers in the layout [QuantumRegister(2, 'qr0'), QuantumRegister(3, 'qr1')]
Returns:
    List: A list of Register in the layout


return self._v2p<EOL>

Returns the dictionary where the keys are virtual (qu)bits and the
values are physical (qu)bits.


return self._p2v<EOL>

Returns the dictionary where the keys are physical (qu)bits and the
values are virtual (qu)bits.


if type(left) is not type(right):<EOL><INDENT>raise LayoutError('<STR_LIT>')<EOL><DEDENT>temp = self[left]<EOL>self[left] = self[right]<EOL>self[right] = temp<EOL>

Swaps the map between left and right.
        Args:
            left (tuple or int): Item to swap with right.
            right (tuple or int): Item to swap with left.
        Raises:
            LayoutError: If left and right have not the same type.


edge_map = dict()<EOL>for virtual, physical in self.get_virtual_bits().items():<EOL><INDENT>if physical not in another_layout._p2v:<EOL><INDENT>raise LayoutError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>edge_map[virtual] = another_layout[physical]<EOL><DEDENT>return edge_map<EOL>

Combines self and another_layout into an "edge map".

        For example::

              self       another_layout  resulting edge map
           qr_1 -> 0        0 <- q_2         qr_1 -> q_2
           qr_2 -> 2        2 <- q_1         qr_2 -> q_1
           qr_3 -> 3        3 <- q_0         qr_3 -> q_0

        The edge map is used to compose dags via, for example, compose_back.

        Args:
            another_layout (Layout): The other layout to combine.
        Returns:
            dict: A "edge map".
        Raises:
            LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises.


layout = Layout()<EOL>for reg in regs:<EOL><INDENT>layout.add_register(reg)<EOL><DEDENT>return layout<EOL>

Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
    *regs (Registers): registers to include in the layout.
Returns:
    Layout: A layout with all the `regs` in the given order.


if not all((isinstance(i, int) for i in int_list)):<EOL><INDENT>raise LayoutError('<STR_LIT>')<EOL><DEDENT>if len(int_list) != len(set(int_list)):<EOL><INDENT>raise LayoutError('<STR_LIT>')<EOL><DEDENT>n_qubits = sum(reg.size for reg in qregs)<EOL>if len(int_list) < n_qubits:<EOL><INDENT>err_msg = '<STR_LIT>'<EOL>raise LayoutError(err_msg)<EOL><DEDENT>out = Layout()<EOL>main_idx = <NUM_LIT:0><EOL>for qreg in qregs:<EOL><INDENT>for idx in range(qreg.size):<EOL><INDENT>out[(qreg, idx)] = int_list[main_idx]<EOL>main_idx += <NUM_LIT:1><EOL><DEDENT><DEDENT>if main_idx != len(int_list):<EOL><INDENT>for int_item in int_list[main_idx:]:<EOL><INDENT>out[int_item] = None<EOL><DEDENT><DEDENT>return out<EOL>

Converts a list of integers to a Layout
        mapping virtual qubits (index of the list) to
        physical qubits (the list values).

        Args:
            int_list (list): A list of integers.
            *qregs (QuantumRegisters): The quantum registers to apply
                the layout to.
        Returns:
            Layout: The corresponding Layout object.
        Raises:
            LayoutError: Invalid input layout.


out = Layout()<EOL>for physical, virtual in enumerate(tuple_list):<EOL><INDENT>if virtual is None:<EOL><INDENT>continue<EOL><DEDENT>elif Layout.is_virtual(virtual):<EOL><INDENT>if virtual in out._v2p:<EOL><INDENT>raise LayoutError('<STR_LIT>')<EOL><DEDENT>out[virtual] = physical<EOL><DEDENT>else:<EOL><INDENT>raise LayoutError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>return out<EOL>

Populates a Layout from a list containing virtual
qubits---(QuantumRegister, int) tuples---, or None.

Args:
    tuple_list (list):
        e.g.: [qr[0], None, qr[2], qr[3]]
Returns:
    Layout: the corresponding Layout object
Raises:
    LayoutError: If the elements are not (Register, integer) or None


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


return repr(self.msg)<EOL>


q_gate_list = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:h>', '<STR_LIT:x>', '<STR_LIT:y>', '<STR_LIT:z>']<EOL>cancellation_sets = defaultdict(lambda: [])<EOL>for wire in dag.wires:<EOL><INDENT>wire_name = "<STR_LIT>".format(str(wire[<NUM_LIT:0>].name), str(wire[<NUM_LIT:1>]))<EOL>wire_commutation_set = self.property_set['<STR_LIT>'][wire_name]<EOL>for com_set_idx, com_set in enumerate(wire_commutation_set):<EOL><INDENT>if com_set[<NUM_LIT:0>].type in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>for node in com_set:<EOL><INDENT>num_qargs = len(node.qargs)<EOL>if num_qargs == <NUM_LIT:1> and node.name in q_gate_list:<EOL><INDENT>cancellation_sets[(node.name, wire_name, com_set_idx)].append(node)<EOL><DEDENT>if num_qargs == <NUM_LIT:1> and node.name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:t>', '<STR_LIT:s>']:<EOL><INDENT>cancellation_sets[('<STR_LIT>', wire_name, com_set_idx)].append(node)<EOL><DEDENT>elif num_qargs == <NUM_LIT:2> and node.qargs[<NUM_LIT:0>] == wire:<EOL><INDENT>second_op_name = "<STR_LIT>".format(str(node.qargs[<NUM_LIT:1>][<NUM_LIT:0>].name),<EOL>str(node.qargs[<NUM_LIT:1>][<NUM_LIT:1>]))<EOL>q2_key = (node.name, wire_name, second_op_name,<EOL>self.property_set['<STR_LIT>'][(node, second_op_name)])<EOL>cancellation_sets[q2_key].append(node)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for cancel_set_key in cancellation_sets:<EOL><INDENT>set_len = len(cancellation_sets[cancel_set_key])<EOL>if ((set_len) > <NUM_LIT:1> and cancel_set_key[<NUM_LIT:0>] in q_gate_list):<EOL><INDENT>gates_to_cancel = cancellation_sets[cancel_set_key]<EOL>for c_node in gates_to_cancel[:(set_len // <NUM_LIT:2>) * <NUM_LIT:2>]:<EOL><INDENT>dag.remove_op_node(c_node)<EOL><DEDENT><DEDENT>elif((set_len) > <NUM_LIT:1> and cancel_set_key[<NUM_LIT:0>] == '<STR_LIT>'):<EOL><INDENT>run = cancellation_sets[cancel_set_key]<EOL>run_qarg = run[<NUM_LIT:0>].qargs[<NUM_LIT:0>]<EOL>total_angle = <NUM_LIT:0.0>  <EOL>for current_node in run:<EOL><INDENT>if (current_node.condition is not None<EOL>or len(current_node.qargs) != <NUM_LIT:1><EOL>or current_node.qargs[<NUM_LIT:0>] != run_qarg):<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>if current_node.name in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>current_angle = float(current_node.op.params[<NUM_LIT:0>])<EOL><DEDENT>elif current_node.name == '<STR_LIT:t>':<EOL><INDENT>current_angle = sympy.pi / <NUM_LIT:4><EOL><DEDENT>elif current_node.name == '<STR_LIT:s>':<EOL><INDENT>current_angle = sympy.pi / <NUM_LIT:2><EOL><DEDENT>total_angle = current_angle + total_angle<EOL><DEDENT>new_op = U1Gate(total_angle)<EOL>new_qarg = (QuantumRegister(<NUM_LIT:1>, '<STR_LIT:q>'), <NUM_LIT:0>)<EOL>new_dag = DAGCircuit()<EOL>new_dag.add_qreg(new_qarg[<NUM_LIT:0>])<EOL>new_dag.apply_operation_back(new_op, [new_qarg])<EOL>dag.substitute_node_with_dag(run[<NUM_LIT:0>], new_dag)<EOL>for current_node in run[<NUM_LIT:1>:]:<EOL><INDENT>dag.remove_op_node(current_node)<EOL><DEDENT><DEDENT><DEDENT>return dag<EOL>

Run the CommutativeCancellation pass on a dag

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

        Returns:
            DAGCircuit: the optimized DAG.

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


new_dag = DAGCircuit()<EOL>for qreg in dag.qregs.values():<EOL><INDENT>new_dag.add_qreg(qreg)<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>new_dag.add_creg(creg)<EOL><DEDENT>global_index_map = {}<EOL>for wire in dag.wires:<EOL><INDENT>if not isinstance(wire[<NUM_LIT:0>], QuantumRegister):<EOL><INDENT>continue<EOL><DEDENT>global_qregs = list(dag.qregs.values())<EOL>global_index_map[wire] = global_qregs.index(wire[<NUM_LIT:0>]) + wire[<NUM_LIT:1>]<EOL><DEDENT>blocks = self.property_set['<STR_LIT>']<EOL>nodes_seen = set()<EOL>for node in dag.topological_op_nodes():<EOL><INDENT>if node in nodes_seen or node.type == '<STR_LIT>' or node.type == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>if blocks and node in blocks[<NUM_LIT:0>]:<EOL><INDENT>block = blocks[<NUM_LIT:0>]<EOL>block_qargs = set()<EOL>for nd in block:<EOL><INDENT>block_qargs |= set(nd.qargs)<EOL><DEDENT>block_width = len(block_qargs)<EOL>q = QuantumRegister(block_width)<EOL>subcirc = QuantumCircuit(q)<EOL>block_index_map = self._block_qargs_to_indices(block_qargs,<EOL>global_index_map)<EOL>for nd in block:<EOL><INDENT>nodes_seen.add(nd)<EOL>subcirc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])<EOL><DEDENT>unitary = UnitaryGate(Operator(subcirc))  <EOL>new_dag.apply_operation_back(<EOL>unitary, sorted(block_qargs, key=lambda x: block_index_map[x]))<EOL>del blocks[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>for block in blocks[<NUM_LIT:1>:]:<EOL><INDENT>if node in block:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>nodes_seen.add(node)<EOL>new_dag.apply_operation_back(node.op, node.qargs, node.cargs)<EOL><DEDENT><DEDENT><DEDENT>return new_dag<EOL>

iterate over each block and replace it with an equivalent Unitary
        on the same wires.


def _block_qargs_to_indices(self, block_qargs, global_index_map):

block_indices = [global_index_map[q] for q in block_qargs]<EOL>ordered_block_indices = sorted(block_indices)<EOL>block_positions = {q: ordered_block_indices.index(global_index_map[q])<EOL>for q in block_qargs}<EOL>return block_positions<EOL>

Map each qubit in block_qargs to its wire position among the block's wires.
Args:
    block_qargs (list): list of qubits that a block acts on
    global_index_map (dict): mapping from each qubit in the
        circuit to its wire position within that circuit
Returns:
    dict: mapping from qarg to position in block


<EOL>self.property_set['<STR_LIT>'] = defaultdict(list)<EOL>for wire in dag.wires:<EOL><INDENT>wire_name = "<STR_LIT>".format(str(wire[<NUM_LIT:0>].name), str(wire[<NUM_LIT:1>]))<EOL>self.property_set['<STR_LIT>'][wire_name] = []<EOL><DEDENT>for node in dag.topological_op_nodes():<EOL><INDENT>for (_, _, edge_data) in dag.edges(node):<EOL><INDENT>edge_name = edge_data['<STR_LIT:name>']<EOL>self.property_set['<STR_LIT>'][(node, edge_name)] = -<NUM_LIT:1><EOL><DEDENT><DEDENT>for wire in dag.wires:<EOL><INDENT>wire_name = "<STR_LIT>".format(str(wire[<NUM_LIT:0>].name), str(wire[<NUM_LIT:1>]))<EOL>for current_gate in dag.nodes_on_wire(wire):<EOL><INDENT>current_comm_set = self.property_set['<STR_LIT>'][wire_name]<EOL>if not current_comm_set:<EOL><INDENT>current_comm_set.append([current_gate])<EOL><DEDENT>if current_gate not in current_comm_set[-<NUM_LIT:1>]:<EOL><INDENT>prev_gate = current_comm_set[-<NUM_LIT:1>][-<NUM_LIT:1>]<EOL>if _commute(current_gate, prev_gate):<EOL><INDENT>current_comm_set[-<NUM_LIT:1>].append(current_gate)<EOL><DEDENT>else:<EOL><INDENT>current_comm_set.append([current_gate])<EOL><DEDENT><DEDENT>temp_len = len(current_comm_set)<EOL>self.property_set['<STR_LIT>'][(current_gate, wire_name)] = temp_len - <NUM_LIT:1><EOL><DEDENT><DEDENT>

Run the pass on the DAG, and write the discovered commutation relations
into the property_set.


super().__init__()<EOL>self.gate = gate<EOL>

Args:
    gate (qiskit.circuit.gate.Gate): Gate to decompose.


<EOL>for node in dag.op_nodes(self.gate):<EOL><INDENT>if not node.op.definition:<EOL><INDENT>continue<EOL><DEDENT>rule = node.op.definition<EOL>decomposition = DAGCircuit()<EOL>decomposition.add_qreg(rule[<NUM_LIT:0>][<NUM_LIT:1>][<NUM_LIT:0>][<NUM_LIT:0>])<EOL>if rule[<NUM_LIT:0>][<NUM_LIT:2>]:<EOL><INDENT>decomposition.add_creg(rule[<NUM_LIT:0>][<NUM_LIT:2>][<NUM_LIT:0>][<NUM_LIT:0>])<EOL><DEDENT>for inst in rule:<EOL><INDENT>decomposition.apply_operation_back(*inst)<EOL><DEDENT>dag.substitute_node_with_dag(node, decomposition)<EOL><DEDENT>return dag<EOL>

Expand a given gate into its decomposition.

        Args:
            dag(DAGCircuit): input dag
        Returns:
            DAGCircuit: output dag where gate was expanded.


cx_runs = dag.collect_runs(["<STR_LIT>"])<EOL>for cx_run in cx_runs:<EOL><INDENT>partition = []<EOL>chunk = []<EOL>for i in range(len(cx_run) - <NUM_LIT:1>):<EOL><INDENT>chunk.append(cx_run[i])<EOL>qargs0 = cx_run[i].qargs<EOL>qargs1 = cx_run[i + <NUM_LIT:1>].qargs<EOL>if qargs0 != qargs1:<EOL><INDENT>partition.append(chunk)<EOL>chunk = []<EOL><DEDENT><DEDENT>chunk.append(cx_run[-<NUM_LIT:1>])<EOL>partition.append(chunk)<EOL>for chunk in partition:<EOL><INDENT>if len(chunk) % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>for n in chunk:<EOL><INDENT>dag.remove_op_node(n)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for n in chunk[<NUM_LIT:1>:]:<EOL><INDENT>dag.remove_op_node(n)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return dag<EOL>

Run one pass of cx cancellation on the circuit

Args:
    dag (DAGCircuit): the directed acyclic graph to run on.
Returns:
    DAGCircuit: Transformed DAG.


super().__init__()<EOL>self._property = property_to_check<EOL>

Args:
    property_to_check (str): The property to check if a fixed point was reached.


<EOL>self.property_set['<STR_LIT>'] = defaultdict(list)<EOL>good_names = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT:id>"]<EOL>block_list = []<EOL>nodes = list(dag.topological_nodes())<EOL>nodes_seen = dict(zip(nodes, [False] * len(nodes)))<EOL>for nd in dag.topological_op_nodes():<EOL><INDENT>group = []<EOL>if nd.name == "<STR_LIT>" and nd.condition is None and not nodes_seen[nd]:<EOL><INDENT>these_qubits = sorted(nd.qargs)<EOL>pred = list(dag.predecessors(nd))<EOL>explore = True<EOL>while explore:<EOL><INDENT>pred_next = []<EOL>if len(pred) == <NUM_LIT:1> and not nodes_seen[pred[<NUM_LIT:0>]]:<EOL><INDENT>pnd = pred[<NUM_LIT:0>]<EOL>if pnd.name in good_names:<EOL><INDENT>if (pnd.name == "<STR_LIT>" and sorted(pnd.qargs) == these_qubits) orpnd.name != "<STR_LIT>":<EOL><INDENT>group.append(pnd)<EOL>nodes_seen[pnd] = True<EOL>pred_next.extend(dag.predecessors(pnd))<EOL><DEDENT><DEDENT><DEDENT>elif len(pred) == <NUM_LIT:2>:<EOL><INDENT>if pred[<NUM_LIT:0>] in dag.predecessors(pred[<NUM_LIT:1>]):<EOL><INDENT>sorted_pred = [pred[<NUM_LIT:1>]]   <EOL><DEDENT>elif pred[<NUM_LIT:1>] in dag.predecessors(pred[<NUM_LIT:0>]):<EOL><INDENT>sorted_pred = [pred[<NUM_LIT:0>]]   <EOL><DEDENT>else:<EOL><INDENT>if pred[<NUM_LIT:0>].name == "<STR_LIT>" and sorted(pred[<NUM_LIT:0>].qargs) == these_qubits:<EOL><INDENT>sorted_pred = [pred[<NUM_LIT:1>]]<EOL><DEDENT>elif pred[<NUM_LIT:1>].name == "<STR_LIT>" and sorted(pred[<NUM_LIT:1>].qargs) == these_qubits:<EOL><INDENT>sorted_pred = [pred[<NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>sorted_pred = pred<EOL><DEDENT><DEDENT>if len(sorted_pred) == <NUM_LIT:2> and sorted_pred[<NUM_LIT:0>].name == "<STR_LIT>" andsorted_pred[<NUM_LIT:1>].name == "<STR_LIT>":<EOL><INDENT>break  <EOL><DEDENT>for pnd in sorted_pred:<EOL><INDENT>if pnd.name not in good_names:<EOL><INDENT>continue<EOL><DEDENT>if pnd.name != "<STR_LIT>":<EOL><INDENT>if not nodes_seen[pnd]:<EOL><INDENT>group.append(pnd)<EOL>nodes_seen[pnd] = True<EOL>pred_next.extend(dag.predecessors(pnd))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>pred_qubits = sorted(pnd.qargs)<EOL>if pred_qubits == these_qubits:<EOL><INDENT>if not nodes_seen[pnd]:<EOL><INDENT>group.append(pnd)<EOL>nodes_seen[pnd] = True<EOL>pred_next.extend(dag.predecessors(pnd))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>these_qubits = list(set(these_qubits) -<EOL>set(pred_qubits))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>pred = list(set(pred_next))<EOL>if not pred:<EOL><INDENT>explore = False<EOL><DEDENT><DEDENT>group.reverse()<EOL>group.append(nd)<EOL>nodes_seen[nd] = True<EOL>these_qubits = sorted(nd.qargs)<EOL>succ = list(dag.successors(nd))<EOL>explore = True<EOL>while explore:<EOL><INDENT>succ_next = []<EOL>if len(succ) == <NUM_LIT:1> and not nodes_seen[succ[<NUM_LIT:0>]]:<EOL><INDENT>snd = succ[<NUM_LIT:0>]<EOL>if snd.name in good_names:<EOL><INDENT>if (snd.name == "<STR_LIT>" and sorted(snd.qargs) == these_qubits) orsnd.name != "<STR_LIT>":<EOL><INDENT>group.append(snd)<EOL>nodes_seen[snd] = True<EOL>succ_next.extend(dag.successors(snd))<EOL><DEDENT><DEDENT><DEDENT>elif len(succ) == <NUM_LIT:2>:<EOL><INDENT>if succ[<NUM_LIT:0>] in dag.successors(succ[<NUM_LIT:1>]):<EOL><INDENT>sorted_succ = [succ[<NUM_LIT:1>]]  <EOL><DEDENT>elif succ[<NUM_LIT:1>] in dag.successors(succ[<NUM_LIT:0>]):<EOL><INDENT>sorted_succ = [succ[<NUM_LIT:0>]]  <EOL><DEDENT>else:<EOL><INDENT>if succ[<NUM_LIT:0>].name == "<STR_LIT>" and sorted(succ[<NUM_LIT:0>].qargs) == these_qubits:<EOL><INDENT>sorted_succ = [succ[<NUM_LIT:1>]]<EOL><DEDENT>elif succ[<NUM_LIT:1>].name == "<STR_LIT>" and sorted(succ[<NUM_LIT:1>].qargs) == these_qubits:<EOL><INDENT>sorted_succ = [succ[<NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>sorted_succ = succ<EOL><DEDENT><DEDENT>if len(sorted_succ) == <NUM_LIT:2> andsorted_succ[<NUM_LIT:0>].name == "<STR_LIT>" andsorted_succ[<NUM_LIT:1>].name == "<STR_LIT>":<EOL><INDENT>break  <EOL><DEDENT>for snd in sorted_succ:<EOL><INDENT>if snd.name not in good_names:<EOL><INDENT>continue<EOL><DEDENT>if snd.name != "<STR_LIT>":<EOL><INDENT>if not nodes_seen[snd]:<EOL><INDENT>group.append(snd)<EOL>nodes_seen[snd] = True<EOL>succ_next.extend(dag.successors(snd))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>succ_qubits = sorted(snd.qargs)<EOL>if succ_qubits == these_qubits:<EOL><INDENT>if not nodes_seen[snd]:<EOL><INDENT>group.append(snd)<EOL>nodes_seen[snd] = True<EOL>succ_next.extend(dag.successors(snd))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>these_qubits = list(set(these_qubits) -<EOL>set(succ_qubits))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>succ = list(set(succ_next))<EOL>if not succ:<EOL><INDENT>explore = False<EOL><DEDENT><DEDENT>block_list.append(tuple(group))<EOL><DEDENT><DEDENT>self.property_set['<STR_LIT>'] = block_list<EOL>return dag<EOL>

collect blocks of adjacent gates acting on a pair of "cx" qubits.

        The blocks contain "op" nodes in topological sort order
        such that all gates in a block act on the same pair of
        qubits and are adjacent in the circuit. the blocks are built
        by examining predecessors and successors of "cx" gates in
        the circuit. u1, u2, u3, cx, id gates will be included.

        Return a list of tuples of "op" node labels.


diagonal_1q_gates = (RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, U1Gate)<EOL>diagonal_2q_gates = (CzGate, CrzGate, Cu1Gate, RZZGate)<EOL>nodes_to_remove = set()<EOL>for measure in dag.op_nodes(Measure):<EOL><INDENT>predecessor = dag.quantum_predecessors(measure)[<NUM_LIT:0>]<EOL>if predecessor.type == '<STR_LIT>' and isinstance(predecessor.op, diagonal_1q_gates):<EOL><INDENT>nodes_to_remove.add(predecessor)<EOL><DEDENT>if predecessor.type == '<STR_LIT>' and isinstance(predecessor.op, diagonal_2q_gates):<EOL><INDENT>successors = dag.quantum_successors(predecessor)<EOL>if all([s.type == '<STR_LIT>' and isinstance(s.op, Measure) for s in successors]):<EOL><INDENT>nodes_to_remove.add(predecessor)<EOL><DEDENT><DEDENT><DEDENT>for node_to_remove in nodes_to_remove:<EOL><INDENT>dag.remove_op_node(node_to_remove)<EOL><DEDENT>return dag<EOL>

Return a new circuit that has been optimized.


super().__init__()<EOL>self.basis = basis<EOL>

Args:
    basis (list[str]): Target basis names to unroll to, e.g. `['u3', 'cx']` .


<EOL>for node in dag.op_nodes():<EOL><INDENT>basic_insts = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if node.name in basic_insts:<EOL><INDENT>continue<EOL><DEDENT>if node.name in self.basis:  <EOL><INDENT>continue<EOL><DEDENT>rule = node.op.definition<EOL>if not rule:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(str(self.basis), node.op.name))<EOL><DEDENT>decomposition = DAGCircuit()<EOL>decomposition.add_qreg(rule[<NUM_LIT:0>][<NUM_LIT:1>][<NUM_LIT:0>][<NUM_LIT:0>])<EOL>for inst in rule:<EOL><INDENT>decomposition.apply_operation_back(*inst)<EOL><DEDENT>unrolled_dag = self.run(decomposition)  <EOL>dag.substitute_node_with_dag(node, unrolled_dag)<EOL><DEDENT>return dag<EOL>

Expand all op nodes to the given basis.

        Args:
            dag(DAGCircuit): input dag

        Raises:
            QiskitError: if unable to unroll given the basis due to undefined
            decomposition rules (such as a bad basis) or excessive recursion.

        Returns:
            DAGCircuit: output unrolled dag


<EOL>if len(barriers) < <NUM_LIT:2>:<EOL><INDENT>return None<EOL><DEDENT>node_to_barrier_qubits = {}<EOL>current_barrier = barriers[<NUM_LIT:0>]<EOL>end_of_barrier = current_barrier<EOL>current_barrier_nodes = [current_barrier]<EOL>current_qubits = set(current_barrier.qargs)<EOL>current_ancestors = dag.ancestors(current_barrier)<EOL>current_descendants = dag.descendants(current_barrier)<EOL>barrier_to_add = Barrier(len(current_qubits))<EOL>for next_barrier in barriers[<NUM_LIT:1>:]:<EOL><INDENT>next_ancestors = {nd for nd in dag.ancestors(next_barrier)<EOL>if nd not in current_barrier_nodes}<EOL>next_descendants = {nd for nd in dag.descendants(next_barrier)<EOL>if nd not in current_barrier_nodes}<EOL>next_qubits = set(next_barrier.qargs)<EOL>if (<EOL>not current_qubits.isdisjoint(next_qubits)<EOL>and current_ancestors.isdisjoint(next_descendants)<EOL>and current_descendants.isdisjoint(next_ancestors)<EOL>):<EOL><INDENT>current_ancestors = current_ancestors | next_ancestors<EOL>current_descendants = current_descendants | next_descendants<EOL>current_qubits = current_qubits | next_qubits<EOL>barrier_to_add = Barrier(len(current_qubits))<EOL><DEDENT>else:<EOL><INDENT>if barrier_to_add:<EOL><INDENT>node_to_barrier_qubits[end_of_barrier] = current_qubits<EOL><DEDENT>current_qubits = set(next_barrier.qargs)<EOL>current_ancestors = dag.ancestors(next_barrier)<EOL>current_descendants = dag.descendants(next_barrier)<EOL>barrier_to_add = Barrier(len(current_qubits))<EOL>current_barrier_nodes = []<EOL><DEDENT>end_of_barrier = next_barrier<EOL>current_barrier_nodes.append(end_of_barrier)<EOL><DEDENT>if barrier_to_add:<EOL><INDENT>node_to_barrier_qubits[end_of_barrier] = current_qubits<EOL><DEDENT>return node_to_barrier_qubits<EOL>

Returns a dict of DAGNode : Barrier objects, where the barrier needs to be
inserted where the corresponding DAGNode appears in the main DAG


resets = dag.op_nodes(Reset)<EOL>for reset in resets:<EOL><INDENT>predecessor = next(dag.predecessors(reset))<EOL>if predecessor.type == '<STR_LIT>':<EOL><INDENT>dag.remove_op_node(reset)<EOL><DEDENT><DEDENT>return dag<EOL>


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>

Choose a TrivialLayout.

Args:
    coupling_map (Coupling): directed graph representing a coupling map.

Raises:
    TranspilerError: if invalid options


num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])<EOL>if num_dag_qubits > self.coupling_map.size():<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>self.property_set['<STR_LIT>'] = Layout.generate_trivial_layout(*dag.qregs.values())<EOL>

Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1.

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

Raises:
    TranspilerError: if dag wider than self.coupling_map


def _layer_permutation(layer_partition, initial_layout, layout, qubit_subset,<EOL>coupling, trials, qregs, rng):

logger.debug("<STR_LIT>",<EOL>pformat(layer_partition))<EOL>logger.debug("<STR_LIT>",<EOL>pformat(layout.get_virtual_bits()))<EOL>logger.debug("<STR_LIT>",<EOL>pformat(qubit_subset))<EOL>logger.debug("<STR_LIT>", trials)<EOL>gates = []  <EOL>for gate_args in layer_partition:<EOL><INDENT>if len(gate_args) > <NUM_LIT:2>:<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>elif len(gate_args) == <NUM_LIT:2>:<EOL><INDENT>gates.append(tuple(gate_args))<EOL><DEDENT><DEDENT>logger.debug("<STR_LIT>", pformat(gates))<EOL>dist = sum([coupling.distance(layout[g[<NUM_LIT:0>]], layout[g[<NUM_LIT:1>]])<EOL>for g in gates])<EOL>logger.debug("<STR_LIT>", dist)<EOL>if dist == len(gates):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>circ = DAGCircuit()<EOL>for register in layout.get_virtual_bits().keys():<EOL><INDENT>if register[<NUM_LIT:0>] not in circ.qregs.values():<EOL><INDENT>circ.add_qreg(register[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>return True, circ, <NUM_LIT:0>, layout, (not bool(gates))<EOL><DEDENT>num_qubits = len(layout)<EOL>best_depth = inf  <EOL>best_edges = None  <EOL>best_circuit = None  <EOL>best_layout = None  <EOL>cdist2 = coupling._dist_matrix**<NUM_LIT:2><EOL>scale = np.zeros((num_qubits, num_qubits))<EOL>int_qubit_subset = regtuple_to_numeric(qubit_subset, qregs)<EOL>int_gates = gates_to_idx(gates, qregs)<EOL>int_layout = nlayout_from_layout(layout, qregs, coupling.size())<EOL>trial_circuit = DAGCircuit()  <EOL>for register in layout.get_virtual_bits().keys():<EOL><INDENT>if register[<NUM_LIT:0>] not in trial_circuit.qregs.values():<EOL><INDENT>trial_circuit.add_qreg(register[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>slice_circuit = DAGCircuit()  <EOL>for register in layout.get_virtual_bits().keys():<EOL><INDENT>if register[<NUM_LIT:0>] not in slice_circuit.qregs.values():<EOL><INDENT>slice_circuit.add_qreg(register[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>edges = np.asarray(coupling.get_edges(), dtype=np.int32).ravel()<EOL>cdist = coupling._dist_matrix<EOL>for trial in range(trials):<EOL><INDENT>logger.debug("<STR_LIT>", trial)<EOL>dist, optim_edges, trial_layout, depth_step = swap_trial(num_qubits, int_layout,<EOL>int_qubit_subset,<EOL>int_gates, cdist2,<EOL>cdist, edges, scale,<EOL>rng)<EOL>logger.debug("<STR_LIT>", dist)<EOL>if dist == len(gates) and depth_step < best_depth:<EOL><INDENT>logger.debug("<STR_LIT>",<EOL>depth_step)<EOL>best_edges = optim_edges<EOL>best_layout = trial_layout<EOL>best_depth = min(best_depth, depth_step)<EOL><DEDENT>if best_depth == <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if best_layout is None:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return False, None, None, None, False<EOL><DEDENT>edgs = best_edges.edges()<EOL>for idx in range(best_edges.size//<NUM_LIT:2>):<EOL><INDENT>slice_circuit.apply_operation_back(<EOL>SwapGate(), [initial_layout[edgs[<NUM_LIT:2>*idx]], initial_layout[edgs[<NUM_LIT:2>*idx+<NUM_LIT:1>]]], [])<EOL><DEDENT>trial_circuit.extend_back(slice_circuit)<EOL>best_circuit = trial_circuit<EOL>logger.debug("<STR_LIT>")<EOL>best_lay = best_layout.to_layout(qregs)<EOL>return True, best_circuit, best_depth, best_lay, False<EOL>

Find a swap circuit that implements a permutation for this layer.

    Args:
        layer_partition (list): The layer_partition is a list of (qu)bit
            lists and each qubit is a tuple (qreg, index).
        initial_layout (Layout): The initial layout passed.
        layout (Layout): The layout is a Layout object mapping virtual
            qubits in the input circuit to physical qubits in the coupling
            graph. It reflects the current positions of the data.
        qubit_subset (list): The qubit_subset is the set of qubits in
            the coupling graph that we have chosen to map into, as tuples
            (Register, index).
        coupling (CouplingMap): Directed graph representing a coupling map.
            This coupling map should be one that was provided to the
            stochastic mapper.
        trials (int): Number of attempts the randomized algorithm makes.
        qregs (OrderedDict): Ordered dict of registers from input DAG.
        rng (RandomState): Random number generator.

    Returns:
        Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag

    Raises:
        TranspilerError: if anything went wrong.


sizes = [qr.size for qr in qregs.values()]<EOL>reg_idx = np.cumsum([<NUM_LIT:0>]+sizes)<EOL>regint = {}<EOL>for ind, qreg in enumerate(qregs.values()):<EOL><INDENT>regint[qreg] = ind<EOL><DEDENT>out = np.zeros(len(items), dtype=np.int32)<EOL>for idx, val in enumerate(items):<EOL><INDENT>out[idx] = reg_idx[regint[val[<NUM_LIT:0>]]]+val[<NUM_LIT:1>]<EOL><DEDENT>return out<EOL>

Takes (QuantumRegister, int) tuples and converts
    them into an integer array.

    Args:
        items (list): List of tuples of (QuantumRegister, int)
                      to convert.
        qregs (dict): List of )QuantumRegister, int) tuples.
    Returns:
        ndarray: Array of integers.


sizes = [qr.size for qr in qregs.values()]<EOL>reg_idx = np.cumsum([<NUM_LIT:0>]+sizes)<EOL>regint = {}<EOL>for ind, qreg in enumerate(qregs.values()):<EOL><INDENT>regint[qreg] = ind<EOL><DEDENT>out = np.zeros(<NUM_LIT:2>*len(gates), dtype=np.int32)<EOL>for idx, gate in enumerate(gates):<EOL><INDENT>out[<NUM_LIT:2>*idx] = reg_idx[regint[gate[<NUM_LIT:0>][<NUM_LIT:0>]]]+gate[<NUM_LIT:0>][<NUM_LIT:1>]<EOL>out[<NUM_LIT:2>*idx+<NUM_LIT:1>] = reg_idx[regint[gate[<NUM_LIT:1>][<NUM_LIT:0>]]]+gate[<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT>return out<EOL>

Converts gate tuples into a nested list of integers.

    Args:
        gates (list): List of (QuantumRegister, int) pairs
                      representing gates.
        qregs (dict): List of )QuantumRegister, int) tuples.

    Returns:
        list: Nested list of integers for gates.


def __init__(self, coupling_map, initial_layout=None,<EOL>trials=<NUM_LIT:20>, seed=None):

super().__init__()<EOL>self.coupling_map = coupling_map<EOL>self.initial_layout = initial_layout<EOL>self.input_layout = None<EOL>self.trials = trials<EOL>self.seed = seed<EOL>self.qregs = None<EOL>self.rng = None<EOL>self.requires.append(BarrierBeforeFinalMeasurements())<EOL>

Map a DAGCircuit onto a `coupling_map` using swap gates.

If initial_layout is not None, we assume the input circuit
has been layed out before running this pass, and that
the layout process yields a DAG, coupling map, and layout
with the following properties:

1. All three have the same number of qubits
2. The layout a bijection from the DAG qubits to the coupling map

For this mapping pass, it may also be necessary that

3. The coupling map is a connected graph

If these are not satisfied, the behavior is undefined.

Args:
    coupling_map (CouplingMap): Directed graph representing a coupling
        map.
    initial_layout (Layout): initial layout of qubits in mapping
    trials (int): maximum number of iterations to attempt
    seed (int): seed for random number generator


if self.initial_layout is None:<EOL><INDENT>if self.property_set["<STR_LIT>"]:<EOL><INDENT>self.initial_layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT><DEDENT>if len(dag.qubits()) != len(self.initial_layout):<EOL><INDENT>raise TranspilerError('<STR_LIT>')<EOL><DEDENT>if len(self.coupling_map.physical_qubits) != len(self.initial_layout):<EOL><INDENT>raise TranspilerError(<EOL>"<STR_LIT>")<EOL><DEDENT>self.input_layout = self.initial_layout.copy()<EOL>self.qregs = dag.qregs<EOL>if self.seed is None:<EOL><INDENT>self.seed = np.random.randint(<NUM_LIT:0>, np.iinfo(np.int32).max)<EOL><DEDENT>self.rng = np.random.RandomState(self.seed)<EOL>logger.debug("<STR_LIT>", self.seed)<EOL>new_dag = self._mapper(dag, self.coupling_map, trials=self.trials)<EOL>return new_dag<EOL>

Run the StochasticSwap pass on `dag`.

Args:
    dag (DAGCircuit): DAG to map.

Returns:
    DAGCircuit: A mapped DAG.

Raises:
    TranspilerError: if the coupling map or the layout are not
    compatible with the DAG


def _layer_permutation(self, layer_partition, layout, qubit_subset,<EOL>coupling, trials):

return _layer_permutation(layer_partition, self.initial_layout,<EOL>layout, qubit_subset,<EOL>coupling, trials,<EOL>self.qregs, self.rng)<EOL>

Find a swap circuit that implements a permutation for this layer.

        The goal is to swap qubits such that qubits in the same two-qubit gates
        are adjacent.

        Based on S. Bravyi's algorithm.

        layer_partition (list): The layer_partition is a list of (qu)bit
            lists and each qubit is a tuple (qreg, index).
        layout (Layout): The layout is a Layout object mapping virtual
            qubits in the input circuit to physical qubits in the coupling
            graph. It reflects the current positions of the data.
        qubit_subset (list): The qubit_subset is the set of qubits in
            the coupling graph that we have chosen to map into, as tuples
            (Register, index).
        coupling (CouplingMap): Directed graph representing a coupling map.
            This coupling map should be one that was provided to the
            stochastic mapper.
        trials (int): Number of attempts the randomized algorithm makes.

        Returns:
            Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag

        If success_flag is True, then best_circuit contains a DAGCircuit with
        the swap circuit, best_depth contains the depth of the swap circuit,
        and best_layout contains the new positions of the data qubits after the
        swap circuit has been applied. The trivial_flag is set if the layer
        has no multi-qubit gates.

        Raises:
            TranspilerError: if anything went wrong.