Simultaneously measure the expectation of multiple Hermitian matrixes

Hi, I notice that the latest PennyLane supports group measurement of Pauli word. However, when I try to measure two Hermitian matrixes |00><00| and |01><01|, it raised TypeError. Currently, is this type of group measurement not supported? Or is there something wrong with my code? Here is the code.

import pennylane as qml
from pennylane import numpy as np

def get_projector_of_computation_basis(index, n_qubit):
    """generate projector of computational basis as observable

    Args:
        index (int): the index of computational basis |i>
        n_qubit (int): the number of qubits

    Returns:
        _type_: _description_
    """
    state_01 = {'0': np.array([1, 0]), '1':np.array([0, 1])}
    state_basis = 1
    index_bin = bin(index)[2:].rjust(n_qubit, '0')
    for i in range(n_qubit):
        state_basis = np.kron(state_basis, state_01[index_bin[n_qubit-i-1]])
    return qml.Hermitian(np.outer(state_basis, state_basis), wires=[i for i in range(n_qubit)])

dev = qml.device("default.qubit", wires=2)

@qml.qnode(dev)
def circuit(x, obs=None):
    qml.RX(x, wires=0)
    qml.Hadamard(wires=1)
    qml.CNOT(wires=[0, 1])
    return [qml.expval(ob) for ob in obs]

obs = [get_projector_of_computation_basis(0, 2), get_projector_of_computation_basis(1, 2)]

print(circuit(0.5, obs))

Looking forward to your advice.

Thanks.

Hey @Yang!

BTW, you don’t have to go through so much to get projectors. PennyLane’s got you covered :muscle:

https://docs.pennylane.ai/en/stable/code/api/pennylane.Projector.html

The reason your error is occurring is because some wires are being measured multiple times. PennyLane tries to come up with qubit-wise commuting groups for the two observables being measured, but hit an error because qml.Hermitian is being used. The grouping logic is only supported for Pauli observables, hence the error message!

It looks like you’ll have to run your circuit serially. Here is an example using qml.Projector :smile:

dev = qml.device("default.qubit", wires=2)

@qml.qnode(dev)
def circuit(state):
    return qml.expval(qml.Projector(np.array(state), wires=dev.wires))

states = [[0,0], [1,1]]

for state in states:
    print(circuit(state))
1 Like

Hi @isaacdevlugt, thank you for the advice. It is convenient that PennyLane provides qml.Projector. I will have a try.

1 Like

Let us know if you have any other issues with your code!