VisibleDeprecationWarning - 这是从哪里来的?

时间:2017-09-17 21:59:32

标签: python python-3.x runtime-error quantum-computing

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

错误

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

要获得错误......

这是我输入错误的输入/输出。

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

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

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

1 个答案:

答案 0 :(得分:3)

  

它没有说出导致它的哪一行,所以我甚至不知道从哪里开始修复它,我以前从未见过它。

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

所以你可以在前面加上:

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出现的其他位置。