# Optimizing a cavity-qubit system

I want to simulate an optical cavity interacting with a two-level system (a qubit) that depends on some parameters that I then want to optimize. My knowledge on Pennylane/StrawberryFields is very limited, so this is probably a very basic question.

I understand that I should instantiate two devices:

``````cavity_device = qml.device('default.qubit', wires=1)
qubit_device = qml.device('default.gaussian', wires=1)
``````

with which I should then create one (or two?) QNode(s). The qubit is prepared in a state that depends on some parameters. Then the qubit and the cavity interact according to a Jaynes-Cummings interaction for some time, after which the state of the cavity depends on the parameters with which the qubit was prepared. After this interaction, the qubit gets traced out and a loss function gets computed for the cavity.

My question is how to set up this optimization problem in such a way that I will be able to take gradients of a loss function in the cavity side that implicitly depends on the parameters of the qubit. Any help will be appreciated.

Hey @jolle! Welcome to the forum !

Iâ€™m not sure I understand the nuances of your problem. But, if there are any parameters in your circuit that you want to differentiate over, you can â€śflagâ€ť them to PennyLane as differentiable with `requires_grad = True`. For parameters that you donâ€™t want to differentiate over, you would specify `False` instead. Hereâ€™s an example of a circuit with one qubit and two rotation gates, one of which I want to flag in order to take derivatives of.

``````import pennylane as qml
from pennylane import numpy as np
dev = qml.device("default.qubit", wires=1)

@qml.qnode(dev)
def circuit(angle1, angle2):
qml.RX(angle1, wires=0)
qml.RY(angle2, wires=0)
return qml.expval(qml.PauliX(0))

angle1 = np.array(np.pi/3, requires_grad=True) # Differentiate w.r.t. this angle
angle2 = np.array(np.pi/4, requires_grad=False) # will remain constant

angles = [angle1, angle2]

for _ in range(3):
angles, loss = opt.step_and_cost(circuit, *angles)
print(angles)

'''output:
0.29.1
'''
``````

Note that `angle1` changes, while `angle2` does not!

I hope this helps, but if it doesnâ€™t, please respond back with more questions!

1 Like

Unfortunately this wasnâ€™t really my question. My question is more whether there is support for a `qml.device` that includes both a cavity (i.e. a quantum harmonic oscillator Hilbert space) and qubits, or whether there is a way to combine two different devices into a single device