VisibleDeprecationWarning - 这是从哪里来的?

VisibleDeprecationWarning - where is this coming from?

我正在编写一些代码来模拟 python 中的量子计算机。我刚刚添加了一个开始集成大于一个量子位功能的部分,然后出现了这个奇怪的错误。它没有说明是哪条线引起的,所以我什至不知道从哪里开始修复它,而且我以前从未见过它。此外,该程序保持 运行ning 并在我 运行 的几个测试用例中输出正确答案,即使出现此错误也是如此。

错误

Warning (from warnings module):
  File "/usr/lib/python3/dist-packages/numpy/lib/twodim_base.py", line 233
    m = zeros((N, M), dtype=dtype)
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future

Warning (from warnings module):
  File "/usr/lib/python3/dist-packages/numpy/lib/twodim_base.py", line 240
    m[:M-k].flat[i::M+1] = 1

VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future

完整节目

import cmath
import numpy as np
import math
from random import randint

def gate_scale(gate, ap_qubit):
    dimensions = math.sqrt(np.size(gate))
    ap_qubit-=1
    if 2**qnum == dimensions:
        return gate
    else:
        iterator = 1
        kron_num = []
        identity = np.identity(dimensions, np.matrix)
        while iterator <= dimensions:
            kron_num.append(identity)
            iterator+=1
        kron_num[ap_qubit] = gate
        kron_iterator = list(range(len(kron_num)))
        for i in kron_iterator:
            if i == 0:
                x = kron_num[i]
            if i > 0:
                x = np.kron(x, kron_num[i])
        return x

def hadop(qstat, ap_qubit):
    matrix = (1/cmath.sqrt(2))*np.array([[1,1],[1,-1]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix, qstat)

def xop(qstat, ap_qubit):
    matrix = np.array([[0,1],[1,0]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix,qstat)

def zop(qstat, ap_qubit):
    matrix = np.array([[1,0],[0,-1]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix,qstat)

def yop(qstat, ap_qubit):
    matrix = np.array([[0, cmath.sqrt(-1)],[-1*cmath.sqrt(-1),0]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix,qstat)

def sqrtxop(qstat, ap_qubit):
    const1 = 1+cmath.sqrt(1)
    const2 = 1-cmath.sqrt(1)
    matrix = np.array([[const1/2,const2/2],[const2/2,const1/2]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix,qstat)

def phaseshiftop(qstat, ap_qubit):
    phasepos = [math.pi/4, math.pi/2]
    print(phasepos)
    x = input("Please pick one of the two phase shifts, 0 for the first, 1 for the second: ")
    if x == "0":
        y = phasepos[0]
    elif x == "1":
        y = phasepos[1]
    const1 = cmath.sqrt(-1)*y
    matrix = np.array([[1,0],[0,math.e**const1]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix,qstat)

#use of eval because I want the user to be able to input constants, etc
def customop(qstat):
    dimension = eval(input("What are the dimensions of your (square) matrix? Please input a single number: "))
    ls = [] 
    for y in range(dimension): 
        for x in range(dimension): 
            ls.append(float(input('What value for position ({}, {}): '.format(y+1, x+1))))
            matrix = np.matrix(np.resize(ls, (dimension, dimension)))
    #check if matrix is unitary
    if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(dimension)) == True:
        return np.dot(matrix, qstat)
    else:
        print("matrix not unitary, pretending none was applied")
        return qstat

def probability(qstat, n): #fix to handle larger state vectors (see printing)
    if n == 0:
        return (qstat[0])**2
    elif n == 1:
        return (qstat[-1])**2

def measurement(qstat, ap_qubit): #fix to handle larger state vectors
    prob1 = probability(qstat,0)
    prob2 = probability(qstat,1)
    random = randint(0,1)
    if random <= prob1:
        qstat = np.array([0,1])
    elif prob1 < random:
        qstat = np.array([1,0])
    return qstat

qnum = int(input("how many qubits: "))
zero_state = np.matrix([[1],[0]])
one_state = np.matrix([[0],[1]])
z_or_o = input('would you like to start in the 0 or 1 state: ')
iterate = 1
while iterate <= qnum:
    if iterate == 1:
        if z_or_o == '0':
            x = zero_state
        elif z_or_o == '1':
            x = one_state
    if iterate == qnum:
        qstat = x
        print(qstat)
    else:
        x = np.kron(x,zero_state)
    iterate+=1


gates = {"Hadamard":hadop, "X":xop, "Z":zop, "Y":yop, "sqrtX":sqrtxop,"phase shift":phaseshiftop,"measurement":measurement,"custom":customop}#, "control":control, "target":target
print(gates.keys())

done = "n"#needs to handle more than 1 qubit
while done == "n":
    if qnum == 1:
        fstgat = input("what gate would you like to use? use the list of gates at the top minus control and target: ")
        ap_qubit = int(input("what qubit would you like it to be applied to?"))#handling control/target...
        if fstgat in gates:
            qstat = gates[fstgat](qstat,ap_qubit)
            done = input("Done with your circuit? y or n: ")
        else:
            print("sorry, that gate is not yet implemented. maybe try custom gate.")
    else:
        fstgat = input('what gate would you like to use? (proceed at your own risk): ')
        ap_qubit = int(input('what qubit would you like that gate to be applied to: '))
        if fstgat in gates:
            qstat = gates[fstgat](qstat,ap_qubit)
            done = input('done with your circuit? y or n: ')
        else:
            print('sorry, gate not implemented, maybe try custom gate.')

#printing - fix to handle larger state vectors
print(" ")
print("final state:", qstat)
print("probability of |0> state upon measurement is", probability(qstat,0))#this needs to iterate for qubits
print("probability of |1> state upon measurement is", probability(qstat,1))

(我把所有这些都包括进来是因为我不知道代码是从哪里来的。)

最小化代码

import cmath
import numpy as np
import math
from random import randint

def gate_scale(gate, ap_qubit):
    dimensions = math.sqrt(np.size(gate))
    ap_qubit-=1
    if 2**qnum == dimensions:
        return gate
    else:
        iterator = 1
        kron_num = []
        identity = np.identity(dimensions, np.matrix)
        while iterator <= dimensions:
            kron_num.append(identity)
            iterator+=1
        kron_num[ap_qubit] = gate
        kron_iterator = list(range(len(kron_num)))
        for i in kron_iterator:
            if i == 0:
                x = kron_num[i]
            if i > 0:
                x = np.kron(x, kron_num[i])
        return x

def xop(qstat, ap_qubit):
    matrix = np.array([[0,1],[1,0]])
    matrix = gate_scale(matrix, ap_qubit)
    return np.dot(matrix,qstat)

def probability(qstat, n): #fix to handle larger state vectors (see printing)
    if n == 0:
        return (qstat[0])**2
    elif n == 1:
        return (qstat[-1])**2

def measurement(qstat, ap_qubit): #fix to handle larger state vectors
    prob1 = probability(qstat,0)
    prob2 = probability(qstat,1)
    random = randint(0,1)
    if random <= prob1:
        qstat = np.array([0,1])
    elif prob1 < random:
        qstat = np.array([1,0])
    return qstat

qnum = int(input("how many qubits: "))
zero_state = np.matrix([[1],[0]])
one_state = np.matrix([[0],[1]])
z_or_o = input('would you like to start in the 0 or 1 state: ')
iterate = 1
while iterate <= qnum:
    if iterate == 1:
        if z_or_o == '0':
            x = zero_state
        elif z_or_o == '1':
            x = one_state
    if iterate == qnum:
        qstat = x
        print(qstat)
    else:
        x = np.kron(x,zero_state)
    iterate+=1


gates = {"Hadamard":hadop, "X":xop, "Z":zop, "Y":yop, "sqrtX":sqrtxop,"phase shift":phaseshiftop,"measurement":measurement,"custom":customop}#, "control":control, "target":target
print(gates.keys())

done = "n"#needs to handle more than 1 qubit
while done == "n":
    if qnum == 1:
        fstgat = input("what gate would you like to use? use the list of gates at the top minus control and target: ")
        ap_qubit = int(input("what qubit would you like it to be applied to?"))#handling control/target...
        if fstgat in gates:
            qstat = gates[fstgat](qstat,ap_qubit)
            done = input("Done with your circuit? y or n: ")
        else:
            print("sorry, that gate is not yet implemented. maybe try custom gate.")
    else:
        fstgat = input('what gate would you like to use? (proceed at your own risk): ')
        ap_qubit = int(input('what qubit would you like that gate to be applied to: '))
        if fstgat in gates:
            qstat = gates[fstgat](qstat,ap_qubit)
            done = input('done with your circuit? y or n: ')
        else:
            print('sorry, gate not implemented, maybe try custom gate.')

#printing - fix to handle larger state vectors
print(" ")
print("final state:", qstat)
print("probability of |0> state upon measurement is", probability(qstat,0))#this needs to iterate for qubits
print("probability of |1> state upon measurement is", probability(qstat,1))

获取错误...

这是我遇到错误的 input/output。

how many qubits: 2
would you like to start in the 0 or 1 state: 0
[[1]
 [0]
 [0]
 [0]]
dict_keys(['X', 'sqrtX', 'Hadamard', 'Z', 'phase shift', 'measurement', 'custom', 'Y'])
what gate would you like to use? (proceed at your own risk): X
what qubit would you like that gate to be applied to: 1

打印错误后,它将继续正常进行。

我很乐意添加任何其他必要的信息;让我知道。任何帮助将不胜感激。

It doesn't say anything about which line caused it, so I don't really even know where to start fixing it, and I've never seen it before.

一种简单的方法是将警告升级为异常,然后使用调试器检查变量。

所以你可以在前面加上这个:

import warnings

warnings.simplefilter("error", np.VisibleDeprecationWarning)

然后运行你的代码:

how many qubits: 2
would you like to start in the 0 or 1 state: 0
[[1]
 [0]
 [0]
 [0]]
dict_keys(['X', 'Z', 'sqrtX', 'Hadamard', 'measurement', 'Y', 'custom', 'phase shift'])
what gate would you like to use? (proceed at your own risk): X
what qubit would you like that gate to be applied to: 1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-e3d1cca2e826> in <module>()
    136         ap_qubit = int(input('what qubit would you like that gate to be applied to: '))
    137         if fstgat in gates:
--> 138             qstat = gates[fstgat](qstat,ap_qubit)
    139             done = input('done with your circuit? y or n: ')
    140         else:

<ipython-input-43-e3d1cca2e826> in xop(qstat, ap_qubit)
     36 def xop(qstat, ap_qubit):
     37     matrix = np.array([[0,1],[1,0]])
---> 38     matrix = gate_scale(matrix, ap_qubit)
     39     return np.dot(matrix,qstat)
     40 

<ipython-input-43-e3d1cca2e826> in gate_scale(gate, ap_qubit)
     16         iterator = 1
     17         kron_num = []
---> 18         identity = np.identity(dimensions, np.matrix)
     19         while iterator <= dimensions:
     20             kron_num.append(identity)

-\lib\site-packages\numpy\core\numeric.py in identity(n, dtype)
   2392     """
   2393     from numpy import eye
-> 2394     return eye(n, dtype=dtype)
   2395 
   2396 

\lib\site-packages\numpy\lib\twodim_base.py in eye(N, M, k, dtype)
    178     if M is None:
    179         M = N
--> 180     m = zeros((N, M), dtype=dtype)
    181     if k >= M:
    182         return m

TypeError: 'float' object cannot be interpreted as an integer

然后使用post-mortem analysis:

import pdb

pdb.pm()


> \lib\site-packages\numpy\lib\twodim_base.py(180)eye()
-> m = zeros((N, M), dtype=dtype)
(Pdb) args
N = 2.0
M = 2.0
k = 0
dtype = <class 'numpy.matrixlib.defmatrix.matrix'>
(Pdb) u
> \lib\site-packages\numpy\core\numeric.py(2394)identity()
-> return eye(n, dtype=dtype)
(Pdb) args
n = 2.0
dtype = <class 'numpy.matrixlib.defmatrix.matrix'>

如您所见,您传入了一个浮点数,但它需要一个整数。修复此警告后,您可以再次 运行 代码,看看是否还需要修复出现 VisibleDeprecationWarning 的其他地方。