Exemplo n.º 1
0
def plot_state(quantum_state, method='city', filename=None):
    """Plot the quantum state.

    Args:
        quantum_state (ndarray): statevector or density matrix
                                 representation of a quantum state.
        method (str): Plotting method to use.
        filename (str): the output file to save the plot as. If specified it
            will save and exit and not open up the plot in a new window. If
            `bloch` method is used a `-n` will be added to the filename before
            the extension for each qubit.

    Raises:
        VisualizationError: if the input is not a statevector or density
        matrix, or if the state is not an multi-qubit quantum state.
    """

    # Check if input is a statevector, and convert to density matrix
    rho = np.array(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(len(rho)))
    if 2**num != len(rho):
        raise VisualizationError("Input is not a multi-qubit quantum state.")

    if method == 'city':
        plot_state_city(rho, filename=filename)
    elif method == "paulivec":
        plot_state_paulivec(rho, filename=filename)
    elif method == "qsphere":
        plot_state_qsphere(rho, filename=filename)
    elif method == "bloch":
        orig_filename = filename
        for i in range(num):
            if orig_filename:
                filename_parts = orig_filename.split('.')
                filename_parts[-2] += '-%d' % i
                filename = '.'.join(filename_parts)
                print(filename)
            pauli_singles = [
                Pauli.pauli_single(num, i, 'X'),
                Pauli.pauli_single(num, i, 'Y'),
                Pauli.pauli_single(num, i, 'Z')
            ]
            bloch_state = list(
                map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
                    pauli_singles))
            plot_bloch_vector(bloch_state,
                              "qubit " + str(i),
                              filename=filename)
    elif method == "wigner":
        plot_wigner_function(rho, filename=filename)
    elif method == "hinton":
        plot_hinton(rho, filename=filename)
Exemplo n.º 2
0
def iplot_state(quantum_state, method='city', figsize=None):
    """Plot the quantum state.

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

    Raises:
        VisualizationError: if the input is not a statevector or density
        matrix, or if the state is not an multi-qubit quantum state.
    """
    warnings.warn(
        "iplot_state is deprecated, and will be removed in \
                  the 0.9 release. Use the iplot_state_ * functions \
                  instead.", DeprecationWarning)
    rho = _validate_input_state(quantum_state)
    if method == "city":
        iplot_state_city(rho, figsize=figsize)
    elif method == "paulivec":
        iplot_state_paulivec(rho, figsize=figsize)
    elif method == "qsphere":
        iplot_state_qsphere(rho, figsize=figsize)
    elif method == "bloch":
        iplot_bloch_multivector(rho, figsize=figsize)
    elif method == "hinton":
        iplot_state_hinton(rho, figsize=figsize)
    else:
        raise VisualizationError('Invalid plot state method.')
Exemplo n.º 3
0
def bit_string_index(text):
    """Return the index of a string of 0s and 1s."""
    n = len(text)
    k = text.count("1")
    if text.count("0") != n - k:
        raise VisualizationError("s must be a string of 0 and 1")
    ones = [pos for pos, char in enumerate(text) if char == "1"]
    return lex_index(n, k, ones)
def plot_state(quantum_state, method='city'):
    """Plot the quantum state.

    Args:
        quantum_state (ndarray): statevector or density matrix
                                 representation of a quantum state.
        method (str): Plotting method to use.

    Raises:
        VisualizationError: if the input is not a statevector or density
        matrix, or if the state is not an multi-qubit quantum state.
    """

    # Check if input is a statevector, and convert to density matrix
    rho = np.array(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(len(rho)))
    if 2**num != len(rho):
        raise VisualizationError("Input is not a multi-qubit quantum state.")

    if method == 'city':
        plot_state_city(rho)
    elif method == "paulivec":
        plot_state_paulivec(rho)
    elif method == "qsphere":
        plot_state_qsphere(rho)
    elif method == "bloch":
        for i in range(num):
            bloch_state = list(
                map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
                    pauli_singles(i, num)))
            plot_bloch_vector(bloch_state, "qubit " + str(i))
    elif method == "wigner":
        plot_wigner_function(rho)
Exemplo n.º 5
0
def iplot_state(quantum_state, method='city', options=None):
    """Plot the quantum state.

    Args:
        quantum_state (ndarray): statevector or density matrix
                                 representation of a quantum state.
        method (str): Plotting method to use.
        options (dict): Plotting settings.

    Raises:
        VisualizationError: if the input is not a statevector or density
        matrix, or if the state is not an multi-qubit quantum state.
    """

    # Check if input is a statevector, and convert to density matrix
    rho = np.array(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(len(rho)))
    if 2**num != len(rho):
        raise VisualizationError("Input is not a multi-qubit quantum state.")

    if method == "city":
        iplot_cities(rho, options)
    elif method == "paulivec":
        iplot_paulivec(rho, options)
    elif method == "qsphere":
        iplot_qsphere(rho, options)
    elif method == "bloch":
        iplot_blochsphere(rho, options)
    elif method == "hinton":
        iplot_hinton(rho, options)
    else:
        print("Unknown method '" + method + "'.")
Exemplo n.º 6
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 plot_state(quantum_state, method='city', filename=None, show=False):
    """Plot the quantum state.

    Args:
        quantum_state (ndarray): statevector or density matrix
                                 representation of a quantum state.
        method (str): Plotting method to use.
        filename (str): the output file to save the plot as. If specified it
            will save and exit and not open up the plot in a new window. If
            `bloch` method is used a `-n` will be added to the filename before
            the extension for each qubit.
        show (bool): If set to true the rendered image will open in a new
            window
    Returns:
         matplotlib.Figure: The matplotlib.Figure of the visualization
    Raises:
        VisualizationError: if the input is not a statevector or density
        matrix, or if the state is not an multi-qubit quantum state.
    """

    # Check if input is a statevector, and convert to density matrix
    rho = np.array(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(len(rho)))
    if 2**num != len(rho):
        raise VisualizationError("Input is not a multi-qubit quantum state.")
    fig = None
    if method == 'city':
        fig = plot_state_city(rho, filename=filename, show=show)
    elif method == "paulivec":
        fig = plot_state_paulivec(rho, filename=filename, show=show)
    elif method == "qsphere":
        fig = plot_state_qsphere(rho, filename=filename, show=show)
    elif method == "bloch":
        aspect = float(1 / num)
        fig = plt.figure(figsize=plt.figaspect(aspect))
        for i in range(num):
            ax = fig.add_subplot(1, num, i + 1, projection='3d')
            pauli_singles = [
                Pauli.pauli_single(num, i, 'X'),
                Pauli.pauli_single(num, i, 'Y'),
                Pauli.pauli_single(num, i, 'Z')
            ]
            bloch_state = list(
                map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
                    pauli_singles))
            plot_bloch_vector(bloch_state, "qubit " + str(i), ax=ax)
        if filename:
            plt.savefig(filename)
        elif show:
            plt.show()
    elif method == "wigner":
        fig = plot_wigner_function(rho, filename=filename, show=show)
    elif method == "hinton":
        fig = plot_hinton(rho, filename=filename, show=show)
    return fig