Exemplo n.º 1
0
def bit_string_index(s):
    """Return the index of a string of 0s and 1s."""
    n = len(s)
    k = s.count("1")
    if s.count("0") != n - k:
        raise VisualizationError("s must be a string of 0 and 1")
    ones = [pos for pos, char in enumerate(s) if char == "1"]
    return lex_index(n, k, ones)
Exemplo n.º 2
0
def _validate_input_state(quantum_state):
    """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.
    """
    rho = np.asarray(quantum_state)
    if rho.ndim == 1:
        rho = np.outer(rho, np.conj(rho))
    # Check the shape of the input is a square matrix
    shape = np.shape(rho)
    if len(shape) != 2 or shape[0] != shape[1]:
        raise VisualizationError("Input is not a valid quantum state.")
    # Check state is an n-qubit state
    num = int(np.log2(rho.shape[0]))
    if 2**num != rho.shape[0]:
        raise VisualizationError("Input is not a multi-qubit quantum state.")
    return rho
Exemplo n.º 3
0
def lex_index(n, k, lst):
    """Return  the lex index of a combination..

    Args:
        n (int): the total number of options .
        k (int): The number of elements.
        lst (list): list

    Returns:
        int: returns int index for lex order

    Raises:
        VisualizationError: if length of list is not equal to k
    """
    if len(lst) != k:
        raise VisualizationError("list should have length k")
    comb = list(map(lambda x: n - 1 - x, lst))
    dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
    return int(dualm)
def circuit_drawer(circuit,
                   basis=None,
                   scale=0.7,
                   filename=None,
                   style=None,
                   output=None,
                   interactive=False,
                   line_length=None):
    """Draw a quantum circuit to different formats (set by output parameter):
    0. text: ASCII art string
    1. latex: high-quality images, but heavy external software dependencies
    2. matplotlib: purely in Python with no external dependencies

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

    Args:
        circuit (QuantumCircuit): the quantum circuit to draw
        basis (str): the basis to unroll to prior to drawing. Defaults to
            `"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
            cu3,swap,ccx,cswap"` This option is deprecated and will be removed
            in the future.
        scale (float): scale of image to draw (shrink if < 1)
        filename (str): file path to save image to
        style (dict or str): dictionary of style or file name of style file.
            This option is only used by the `mpl`, `latex`, and `latex_source`
            output types. If a str is passed in that is the path to a json
            file which contains that will be open, parsed, and then used just
            as the input dict.
        output (str): Select the output method to use for drawing the circuit.
            Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
            one is not specified it will use latex and if that fails fallback
            to mpl. However this behavior is deprecated and in a future release
            the default will change.
        interactive (bool): when set true show the circuit in a new window
            (cannot inline in Jupyter). Note when used with the latex_source
            output type this has no effect
        line_length (int): sets the length of the lines generated by `text`
    Returns:
        PIL.Image: (outputs `latex` and `python`) an in-memory representation of
                   the circuit diagram.
        String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
                source code.
    Raises:
        VisualizationError: when an invalid output method is selected

    The style dict kwarg contains numerous options that define the style of the
    output circuit visualization. While the style dict is used by the `mpl`,
    `latex`, and `latex_source` outputs some options in that are only used
    by the `mpl` output. These options are defined below, if it is only used by
    the `mpl` output it is marked as such:

        textcolor (str): The color code to use for text. Defaults to
            `'#000000'` (`mpl` only)
        subtextcolor (str): The color code to use for subtext. Defaults to
            `'#000000'` (`mpl` only)
        linecolor (str): The color code to use for lines. Defaults to
            `'#000000'` (`mpl` only)
        creglinecolor (str): The color code to use for classical register lines
            `'#778899'`(`mpl` only)
        gatetextcolor (str): The color code to use for gate text `'#000000'`
            (`mpl` only)
        gatefacecolor (str): The color code to use for gates. Defaults to
            `'#ffffff'` (`mpl` only)
        barrierfacecolor (str): The color code to use for barriers. Defaults to
            `'#bdbdbd'` (`mpl` only)
        backgroundcolor (str): The color code to use for the background.
            Defaults to `'#ffffff'` (`mpl` only)
        fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
            only)
        subfontsize (int): The font size to use for subtext. Defaults to 8
            (`mpl` only)
        displaytext (dict): A dictionary of the text to use for each element
            type in the output visualization. The default values are:
            {
                'id': 'id',
                'u0': 'U_0',
                'u1': 'U_1',
                'u2': 'U_2',
                'u3': 'U_3',
                'x': 'X',
                'y': 'Y',
                'z': 'Z',
                'h': 'H',
                's': 'S',
                'sdg': 'S^\\dagger',
                't': 'T',
                'tdg': 'T^\\dagger',
                'rx': 'R_x',
                'ry': 'R_y',
                'rz': 'R_z',
                'reset': '\\left|0\\right\\rangle'
            }
            You must specify all the necessary values if using this. There is
            no provision for passing an incomplete dict in. (`mpl` only)
        displaycolor (dict): The color codes to use for each circuit element.
            By default all values default to the value of `gatefacecolor` and
            the keys are the same as `displaytext`. Also, just like
            `displaytext` there is no provision for an incomplete dict passed
            in. (`mpl` only)
        latexdrawerstyle (bool): When set to True enable latex mode which will
            draw gates like the `latex` output modes. (`mpl` only)
        usepiformat (bool): When set to True use radians for output (`mpl`
            only)
        fold (int): The number of circuit elements to fold the circuit at.
            Defaults to 20 (`mpl` only)
        cregbundle (bool): If set True bundle classical registers (`mpl` only)
        plotbarrier (bool): Enable/disable drawing barriers in the output
            circuit. Defaults to True.
        showindex (bool): If set True draw an index. (`mpl` only)
        compress (bool): If set True draw a compressed circuit (`mpl` only)
        figwidth (int): The maximum width (in inches) for the output figure.
            (`mpl` only)
        dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
            only)
        margin (list): `mpl` only
        creglinestyle (str): The style of line to use for classical registers.
            Choices are `'solid'`, `'doublet'`, or any valid matplotlib
            `linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
        reversebits (bool): When set to True reverse the bit order inside
            registers for the output visualization.

    """
    if basis is None:
        basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
                 "cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
    else:
        warnings.warn(
            'The basis kwarg is deprecated and the circuit drawer '
            'function will not be able to adjust basis gates itself '
            'in a future release', DeprecationWarning)

    im = None
    if not output:
        warnings.warn(
            'The current behavior for the default output will change'
            ' in a future release. Instead of trying latex and '
            'falling back to mpl on failure it will just use '
            '"text" by default', DeprecationWarning)
        try:
            im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
        except (OSError, subprocess.CalledProcessError, FileNotFoundError):
            im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
                                            style)
    else:
        if output == 'text':
            reversebits = style[
                'reversebits'] if style and 'reversebits' in style else False
            plotbarriers = style[
                'plotbarriers'] if style and 'plotbarriers' in style else True

            return _text_circuit_drawer(circuit,
                                        filename=filename,
                                        basis=basis,
                                        line_length=line_length,
                                        reversebits=reversebits,
                                        plotbarriers=plotbarriers)
        elif output == 'latex':
            im = _latex_circuit_drawer(circuit,
                                       basis=basis,
                                       scale=scale,
                                       filename=filename,
                                       style=style)
        elif output == 'latex_source':
            return _generate_latex_source(circuit,
                                          basis=basis,
                                          filename=filename,
                                          scale=scale,
                                          style=style)
        elif output == 'mpl':
            im = _matplotlib_circuit_drawer(circuit,
                                            basis=basis,
                                            scale=scale,
                                            filename=filename,
                                            style=style)
        else:
            raise VisualizationError(
                'Invalid output type %s selected. The only valid choices '
                'are latex, latex_source, text, and mpl' % output)
    if im and interactive:
        im.show()
    return im