Ejemplo 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)
Ejemplo n.º 2
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')
Ejemplo n.º 3
0
def iplot_blochsphere(rho, options=None):
    """ Create a bloch sphere representation.

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

        Args:
            rho (array): Density matrix
            options (dict): Representation settings containing
                    - width (integer): graph horizontal size
                    - height (integer): graph vertical size
    """

    # 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>
    """)

    if not options:
        options = {}

    # 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))