XanaduAI / strawberryfields

Strawberry Fields is a full-stack Python library for designing, simulating, and optimizing continuous variable (CV) quantum optical circuits.
https://strawberryfields.ai
Apache License 2.0
747 stars 186 forks source link

Layer's outpout is None when using LossChannel #587

Closed jonasbrami closed 3 years ago

jonasbrami commented 3 years ago

Issue description

I may be missing something, but when trying to add LossChannels to the layer in the quantum_neural_network.py, the output of the layer is None

Python version: 3.8.5 Platform info: Linux-5.8.0-44-generic-x86_64-with-glibc2.10 Installation path: /home/jonas/anaconda3/envs/strawberry/lib/python3.8/site-packages/strawberryfields Strawberry Fields version: 0.17.0 Numpy version: 1.19.2 Scipy version: 1.4.1 SymPy version: 1.7.1 NetworkX version: 2.5 The Walrus version: 0.14.0 Blackbird version: 0.3.1-dev TensorFlow version: 2.2.0

#### Source code and tracebacks

def layer(params, q, loss_channel=None, loss_channel_param=None): """CV quantum neural network layer acting on N modes.

Args:
    params (list[float]): list of length ``2*(max(1, N-1) + N**2 + n)`` containing
        the number of parameters for the layer
    q (list[RegRef]): list of Strawberry Fields quantum registers the layer
        is to be applied to
"""
N = len(q)
M = int(N * (N - 1)) + max(1, N - 1)

int1 = params[:M]
s = params[M:M+N]
int2 = params[M+N:2*M+N]
dr = params[2*M+N:2*M+2*N]
dp = params[2*M+2*N:2*M+3*N]
k = params[2*M+3*N:2*M+4*N]

# begin layer
interferometer(int1, q)

for i in range(N):
    ops.Sgate(s[i]) | q[i]

interferometer(int2, q)

for i in range(N):
    ops.Dgate(dr[i], dp[i]) | q[i]
    ops.Kgate(k[i]) | q[i]
    if i == N-1:
        if loss_channel is None:
            pass
        elif loss_channel == 'vacuum_coupling':
            ops.LossChannel(loss_channel_param) | q[i]
        elif loss_channel == 'thermal_coupling':
            ops.ThermalLossChannel(loss_channel_param) | q[i]
antalszava commented 3 years ago

Hi @jonasbrami, the quantum_neural_network.py tutorial is tailored towards using pure states. Adding loss channels to the circuit might (and in most cases does) result in mixed quantum states. Strawberry Fields keeps track of the purity of the state internally and the state.ket method returns None for mixed states. To adjust the tutorial for using loss channels, the code would likely need to be altered to use state.dm (which returns the state in the density matrix formalism).

I'll remove the bug label, but let us know if you have any related questions. :slightly_smiling_face:

jonasbrami commented 3 years ago

Thanks a lot for the explanation :)