Exemplo n.º 1
0
def bloch_states(rho):
    """Return the values of the Bloch vectors for a given state.

    Taken from plot_bloch_multivector in
    qiskit.visualization.state_visualization.
    """

    if rho.ndim == 1:
        rho = np.outer(rho, np.conj(rho))

    num = int(np.log2(len(rho)))

    ret = []
    for i in range(num):
        pauli_singles = [
            Pauli.pauli_single(num, i, "X"),
            Pauli.pauli_single(num, i, "Y"),
            Pauli.pauli_single(num, i, "Z"),
        ]

        ret.append(
            list(
                map(
                    lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
                    pauli_singles,
                )))

    return ret
Exemplo n.º 2
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.º 3
0
    def test_pauli_single(self):
        """Test pauli single."""
        num_qubits = 5
        pz = Pauli.pauli_single(num_qubits, 2, 'Z')
        self.assertTrue(pz.to_label(), 'IIIZI')

        py = Pauli.pauli_single(num_qubits, 4, 'Y')
        self.assertTrue(py.to_label(), 'IYIII')

        px = Pauli.pauli_single(num_qubits, 3, 'X')
        self.assertTrue(px.to_label(), 'IIXII')
Exemplo n.º 4
0
def plot_bloch_multivector(rho, title='', figsize=None):
    """Plot the Bloch sphere.

    Plot a sphere, axes, the Bloch vector, and its projections onto each axis.

    Args:
        rho (ndarray): Numpy array for state vector or density matrix.
        title (str): a string that represents the plot title
        figsize (tuple): Has no effect, here for compatibility only.

    Returns:
        Figure: A matplotlib figure instance if `ax = None`.

    Raises:
        ImportError: Requires matplotlib.
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('Must have Matplotlib installed.')
    rho = _validate_input_state(rho)
    num = int(np.log2(len(rho)))
    width, height = plt.figaspect(1 / num)
    fig = plt.figure(figsize=(width, height))
    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,
                          figsize=figsize)
    fig.suptitle(title, fontsize=16)
    plt.close(fig)
    return fig
def iplot_bloch_multivector(rho, figsize=None):
    """ Create a bloch sphere representation.

        Graphical representation of the input array, using as much bloch
        spheres as qubit are required.

        Args:
            rho (array): State vector or density matrix
            figsize (tuple): Figure size in pixels.
    """

    # HTML
    html_template = Template("""
    <p>
        <div id="content_$divNumber" style="position: absolute; z-index: 1;">
            <div id="bloch_$divNumber"></div>
        </div>
    </p>
    """)

    # JavaScript
    javascript_template = Template("""
    <script>
        requirejs.config({
            paths: {
                qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
            }
        });
        data = $data;
        dataValues = [];
        for (var i = 0; i < data.length; i++) {
            // Coordinates
            var x = data[i][0];
            var y = data[i][1];
            var z = data[i][2];
            var point = {'x': x,
                        'y': y,
                        'z': z};
            dataValues.push(point);
        }

        require(["qVisualization"], function(qVisualizations) {
            // Plot figure
            qVisualizations.plotState("bloch_$divNumber",
                                      "bloch",
                                      dataValues,
                                      $options);
        });
    </script>
    """)
    rho = _validate_input_state(rho)
    if figsize is None:
        options = {}
    else:
        options = {'width': figsize[0], 'height': figsize[1]}

    # Process data and execute
    num = int(np.log2(len(rho)))

    bloch_data = []
    for i in range(num):
        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))
        bloch_data.append(bloch_state)

    div_number = str(time.time())
    div_number = re.sub('[.]', '', div_number)

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

    javascript = javascript_template.substitute({
        'data': bloch_data,
        'divNumber': div_number,
        'options': options
    })

    display(HTML(html + javascript))
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