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

Avoid `VisibleDeprecationWarning` by specifying `dtype` for `ndarray` #564

Closed antalszava closed 3 years ago

antalszava commented 3 years ago

Newer numpy version (e.g., numpy==1.20.2) raise a warning for constructing ragged arrays:

strawberryfields/backends/states.py:1633: VisibleDeprecationWarning:
Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.

This PR applies the suggestion from the warning message at two places.

codecov[bot] commented 3 years ago

Codecov Report

Merging #564 (011edbe) into master (a2056f7) will increase coverage by 0.00%. The diff coverage is 100.00%.

@@           Coverage Diff           @@
##           master     #564   +/-   ##
=======================================
  Coverage   98.36%   98.36%           
=======================================
  Files          76       76           
  Lines        8332     8336    +4     
=======================================
+ Hits         8196     8200    +4     
  Misses        136      136           
Impacted Files Coverage Δ
strawberryfields/backends/states.py 99.83% <100.00%> (+<0.01%) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update a2056f7...011edbe. Read the comment docs.

antalszava commented 3 years ago

@josh146 had a closer look at this, a ragged array is created even if the user provided vectors have the same length:

import numpy as np
import strawberryfields as sf

nmodes = 2
epsilon = 0.1
sf.hbar = 1
prog_linear_cluster = sf.Program(nmodes)

with prog_linear_cluster.context as q:
    sf.ops.GKP(state=[0.5*np.pi, 0], epsilon=epsilon) | q[0]
    sf.ops.Squeezed(r = -5) | q[1]

eng = sf.Engine("bosonic")
result = eng.run(prog_linear_cluster)
vec = np.linspace(-5, 5, num=200)
sf.plot.plot_wigner(result.state, 0, vec, vec)

Here we use vec twice, and the warning still arises. The reason is, that under the hood we use X, P = np.meshgrid(xvec, pvec, sparse=True), where having sparse=True will change the shape of X and P.

vec = np.linspace(-5, 5, num=200)
mesh = np.meshgrid(vec, vec, sparse=True)
print(mesh[0].shape, mesh[1].shape)

mesh = np.meshgrid(vec, vec)
print(mesh[0].shape, mesh[1].shape)
(1, 200) (200, 1)
(200, 200) (200, 200)

Added a condition nonetheless. :slightly_smiling_face:

josh146 commented 3 years ago

P.S., don't forget to update the changelog!