When cost function depends on several input states

I want to build a slightly different structure of how typical VQE model is designed: the standard VQE attempts to optimize <Ψ(θ)|E|Ψ(θ)> where |Ψ(θ)> = U(θ)|Ψ0>, and is easy to implement on Pennylane. However, I’m a bit lost how to write codes in Pennylane when the cost function depends on several input states simulataneoulsy, for instance consider optimizing: |<Ψ1(θ)|E|Ψ1(θ)>| + |<Ψ2(θ)|E|Ψ2(θ)>|, where Ψ1(θ)> = U(θ)|Ψ1> and Ψ2(θ)> = U(θ)|Ψ2>. It’d be grateful if anyone can let me know how to code these structures. Thank you in advance!

Hey @Jon_Kim!

It sounds like you want something like the following?

@qml.qnode(dev)
def term1(theta):
    U1(theta) # where U1 is pre-defined
    return qml.expval(H)

@qml.qnode(dev)
def term2(theta):
    U2(theta) # where U2 is pre-defined
    return qml.expval(H)

def cost(theta):
    return term1(theta) + term2(theta)

hey @josh, thanks for the response!

It’s similar to what you described, but I want to train a single U with different input states! I assume that your code will train U1 and U2 differently, right?

Ah, if you want to train a single U(\theta), this should work with a slight modification :slightly_smiling_face:

def ansatz(theta):
    # contains parametrized gates

@qml.qnode(dev)
def circuit(theta, input_state):
    qml.MottonenStatePreparation(input_state, wires=...)
    ansatz(theta)
    return qml.expval(H)

def cost(theta, state1, state2):
    return circuit(theta, state1) + circuit(theta, state2)

where you can replace qml.MottonenStatePreparation with any state preparation routine you want :slight_smile:

Great, thanks! I actually have a follow up question after trying precisely what you explained: I made a list that contains measurement operations I want to perform and calculate the cost with such measurement operation. So basically this is precisely what you described in the code but have an extra variable of H in the cost function so that it depends on which observable you would measure. But whenever I print out the list after then, the list doesn’t maintain as a list of measurement operations but rather is changed with expval operation, as shown below. Do you know why is this happening? (Update: I tried some tests and realized two lists of etest before and after are basically the same, so I guess it’s not really a big deal. But still curious why this changes are happening)

@Jon_Kim I don’t quite follow from the Jupyter notebook screenshot :thinking: Do you have more information you could share, including a small, runnable, code snippet you could paste directly here?