VisibleDeprecationWarning - 这是从哪里来的? [英] VisibleDeprecationWarning - where is this coming from?

查看:66
本文介绍了VisibleDeprecationWarning - 这是从哪里来的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing some code to simulate a quantum computer in python. I just added a section which starts integrating greater-than-one-qubit functionality, and then this weird error came up. 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. Further, the program keeps running and outputs the correct answer in the few testcases I've run, even with this error.

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))

(我包括所有这些是因为我不知道代码来自哪里.)

(I'm including all this because I don't know where the code is coming from.)

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))

要获取错误...

这是给我带来错误的输入/输出.

To get the error...

This is the input/output that got the error for me.

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

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

After the error gets printed it continues to carry on normally.

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

I'd be glad to add any other information necessary; just let me know. Any help would be appreciated.

推荐答案

它没有说明是哪条线引起的,所以我真的不知道从哪里开始修复它,而且我以前从未见过它.

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.

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

An easy way would be to promote warnings to exceptions and then use a debugger to inspect the variables.

所以你可以在前面加上:

So you could prepend this:

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

然后使用事后分析:

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 的其他地方.

As you can see you passed in a float but it expected an integer. When you fixed this warning you can run the code again and see if you also need to fix other places where the VisibleDeprecationWarnings came up.

这篇关于VisibleDeprecationWarning - 这是从哪里来的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆