VisibleDeprecationWarning - 这是从哪里来的?

2024-02-07

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

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

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

最小化代码

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

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

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


它没有说明是哪一行引起的,所以我什至不知道从哪里开始修复它,而且我以前从未见过它。

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

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

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

然后使用事后分析 https://docs.python.org/library/pdb.html:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VisibleDeprecationWarning - 这是从哪里来的? 的相关文章

  • Numpy 中矩阵乘以另一个矩阵的每一行

    我有一个大小为 4x4 的齐次变换矩阵和一个大小为 nx3 的轨迹 该轨迹的每一行都是一个向量 我想将齐次变换矩阵乘以轨迹的每一行 下面是代码 append zero column at last trajectory np hstack
  • Matplotlib 颤抖比例

    我正在尝试使用 matplotlib 和 quiver 函数绘制一些箭头 但我想使用数组单独选择每个箭头的长度 http matplotlib sourceforge net api pyplot api html matplotlib p
  • 在类中设置默认值

    我正在用 Python 创建一个类 但我不确定如何正确设置默认值 我的目标是为所有类实例设置默认值 也可以通过类方法对其进行修改 但是 我希望在调用方法后恢复初始默认值 我已经能够使用下面所示的代码使其工作 它不是很 漂亮 所以我怀疑这是解
  • 如何使用Python中的or-tools解决累积旅行商问题?

    累积旅行商问题 CTSP 的目标是最小化到达客户的时间总和 而不是总旅行时间 这与最小化总旅行时间不同 例如 如果一个人拥有无限的车辆 车辆与位置数量相同 并且目标是最大限度地减少到达位置的总时间 则可以为每个位置发送一辆车 因为这是满足所
  • Python NameError,变量“未定义”

    它返回的错误是 NameError name lives is not defined 我知道代码并不是尽可能高效 这是我的第一个项目 但是无论我尝试做什么 都会弹出这个错误 我尝试为其创建一个全局变量 但这没有帮助 我真的很感激一些帮助
  • ModuleNotFoundError:没有名为“pandas.io.formats.csvs”的模块

    我正在尝试创建一个简单的 csv dataframe to csv psv file name encoding utf 8 header True sep doublequote True quoting csv QUOTE ALL in
  • 这个 Python 字符串切片语句中的两个冒号的用途是什么?

    例如 str hello str 1 3 我在 Python 文档中哪里可以找到它 in 序列描述 http docs python org library stdtypes html index 510 s i j k slice of
  • 如何在列表的解析参数中解析列表(字符串)而不是列表(字符)?

    我在flask中使用flask restful 我的代码如下 from flask restful import Resource reqparse apilink parser reqparse RequestParser apilink
  • 检查空查询集

    我想确认这是否是检查空查询集的正确方法 如果这就是为什么我会遇到 UNIQUE 约束错误 syn check Synonym objects filter MD objects get filter dict synonym type St
  • 转置 pandas 数据框

    如何将列表列表转换为 panda 数据框 它不是以列的形式 而是以行的形式 usr bin env python from random import randrange import pandas data randrange 0 100
  • Django Rest Framework 完整性错误捕获

    在 Django Rest Framework 中 我使用了序列化器 视图集和路由器方法 每当我在 django Rest 框架的 API 视图中发布故意错误时 它都会抛出完整性错误 有没有办法尝试捕获错误 例如如果数据中没有错误 则继续保
  • 如何将当前登录的用户指定为模型字段的默认值?

    我想做这样的事情 class Task models Model created by models ForeignKey User default LoggedInUser blank True null True related nam
  • django 创建多类型用户的最佳方法

    我想在 django 中创建多个用户 我想知道哪种方法是最好的 class Teachers models Model user models ForeignKey User is teacher models BooleanField d
  • 如何在lxml,Python中将<转换为<?

    有一个xml文件
  • 找出段落中出现的单词

    sentence Alice was not a bit hurt and she jumped up on to her feet in a moment words Alice jumped played 我可以使用filterpyth
  • pytest 看不到正在测试的函数的日志

    我有一个像这样的烧瓶应用程序 from flask import Flask import logging app Flask name app route def catch all logging warning I m a warni
  • 虎鲸失踪

    使用plotly 导出静态图表时遇到小问题 Plotly 无法正确识别我已安装 orca 并且仍然存在与缺少 orca 相关的错误 我尝试更改 orca 目录 但它仍然无法正常工作 谁知道出了什么问题吗 My code import plo
  • python散景中的反转轴

    我正在尝试反转 y 轴并在散景散点图中设置 x 和 y 的范围 我在用 BokehPlot bokeh scatter data df x range min utc max utc y range min val max val 我收到错
  • 检查数组中是否有 3 个连续值高于某个阈值

    假设我有一个像这样的 np array a 1 3 4 5 60 43 53 4 46 54 56 78 有没有一种快速方法来获取 3 个连续数字都高于某个阈值的所有位置的索引 也就是说 对于某个阈值th 得到所有x其中 a x gt th
  • 从多个 .csv 文件创建混淆矩阵

    我有很多具有以下格式的 csv 文件 338 800 338 550 339 670 340 600 327 500 301 430 299 350 284 339 284 338 283 335 283 330 283 310 282 3

随机推荐

  • 是否有一种 API 方法可以比较 Seq 的内容而不考虑顺序?

    假设 val l1 List 1 2 3 val l2 List 2 3 1 我想要一种方法来确认 l1 等于 l2 内容相同但顺序不同 List Seq 上有 API 方法可以做到这一点吗 l1 sameElements l2 不起作用
  • 假设相同的 lambda 表达式具有不同的类型是否安全?

    我正在试验 lambda 事实上不同的 lambda 表达式具有不同的类型 即使它们是相同的 考虑这段代码 include
  • asp.net:__doPostBack 有时不呈现

    前几天我们遇到了奇怪的错误 doPostBack 未定义 我们正在构建相当先进的网站 但很少使用回发 使用回发的地方之一是 ASP NET 登录状态控件 它是概率性的 有时会被渲染 有时则不会 对于 IE Chrome 它大部分工作正常 但
  • Windows 10 物联网 树莓派 3 wifi 热点

    我正在尝试使用 Windows 10 IoT 核心使我的 RPi 3 成为 AP RPi 通过以太网端口与互联网连接 我想让 RPi 3 内置 WiFi 以与其他设备共享互联网 我读过了文档 https developer microsof
  • 如何使用 ssl 配置创建 Kafka-python 生产者

    我正在尝试使用 ssl 创建 kafka 生产者 我需要有关如何在构造函数中设置 SSL 参数的信息 kafka python 客户端中提供的信息描述性不够 什么是ssl certfile ssl cafile ssl keyfile参数
  • Codeigniter 上传文件无法在线工作,但可以在本地主机上工作

    我想问一下关于codeigniter上传的问题 代码点火器版本 2 1 4 我无法在线将图像上传到文件夹中 但它可以完美地工作localhost 我的上传图片的代码 config upload path assets frontend im
  • 如何在浏览器的任意页面上直接运行jQuery?

    是否有某种编程方式 或者可能是浏览器插件 允许用户在当前加载到浏览器中的网页上任意运行他们想要的任何 jQuery Edit 我的动机是能够提前在页面上测试 jQuery 语法和命令 然后将它们添加到其源代码中 或者向我尝试过的页面的网络管
  • 如何在 swift 中将图标添加到共享表中?

    我在我的 iOS 应用程序中使用共享表 我想弄清楚如何在它打开时将图标添加到它的左上角 我添加了一个照片示例来说明我的意思 我的意思的示例照片 1 IBAction func shareButtonClicked sender Any Se
  • 如何安装和使用WinPcap?

    我今天访问 winpcap org 下载了安装程序 并在我的 Windows 7 笔记本电脑上安装了 WinPcap 但是 安装它的文件夹仅包含安装日志 名为 rpcapd exe 的可执行文件和卸载可执行文件 当我运行 rpcapd ex
  • Twitter API:用户名的 URL 搜索

    我有一个网站列表 我想查看它们是否有 Twitter 帐户 我很好奇 API 中是否有用户名的 url 搜索 或者类似的东西 我一直在阅读和环顾四周 然而 我还不够 当我可以运行一个函数来为我完成这项工作时 我不想手动执行此操作 非常感谢有
  • 当 onClick 设置时,EditText 的 android:nextFocusDown 属性停止工作

    有谁知道为什么 android nextFocusDown 属性在我们设置 onClick 时停止工作 在下面的示例中 我们有一些定义了此属性的 EditText
  • SQL Server 中的列名不明确

    1 https i stack imgur com mQimv png CREATE VIEW planView SELECT planID planName cost quota maxSpeed shapedSpeed typeID t
  • 如何从给定日期获取一个月的最后一天?

    例如 给定日期是1924 年 4 月 4 日我想找出 1924 年二月的最后一天 我想出了 add month 但如果我有来自数据源的不同给定月份 它似乎不灵活 有什么好主意吗 甲骨文有一个last day http docs oracle
  • GCC 错误:命令“gcc-4.0”失败,退出状态为 1

    我正在尝试使用 Xcode 4 2 将 Fabric 安装到 Virtualenv Django 1 3 1 OS X Lion 中 这个错误似乎是相当普遍 https stackoverflow com questions 6906385
  • BigQuery:GHTorrent 何时刷新以及如何获取最新信息?

    The ghtorrent bq数据很高兴有 GitHub 的快照 但是 尚不清楚它何时更新以及我如何获取更多最新数据 理论上 每次发布新的 GHTorrent MySQL 转储时都会更新它 实际上 仍然需要对生成的 CSV 进行手动调整
  • C++ 视频流检测 FPS

    我尝试从轴或 eneo 相机获取视频流的正确 fps rtsp 192 168 0 1 554 axis media media amp I use cv VideoCapture get CV CAP PROP FPS https doc
  • 获取解决方案中使用的所有 NuGet 包的列表

    我正在寻找一种方法 使用命令行脚本而不是在 Visual Studio 中手动获取解决方案 特别是版本 中每个项目中所有使用的 NuGet 包的列表 使用包管理器控制台和命令 Get Package 给了我我想要的东西 但它在 VS 之外不
  • IAP 实际验证收据 (Swift)

    我一直在尝试在我的 spritekit 游戏中实现收据验证 我一直在关注各种教程 基本上最终得到了这段代码 enum RequestURL String case production https buy itunes apple com
  • 尝试让phonegap的Android LocalNotification插件在cordova-1.6.0中工作

    我正在尝试将使用适用于 Android 的 LocalNotification 插件的 Phonegap 1 4 1 项目升级到 cordova 1 6 0 我在这里找到了这个链接 https github com davejohnson
  • VisibleDeprecationWarning - 这是从哪里来的?

    我正在编写一些代码来用 python 模拟量子计算机 我刚刚添加了一个开始集成大于一个量子位功能的部分 然后出现了这个奇怪的错误 它没有说明是哪一行引起的 所以我什至不知道从哪里开始修复它 而且我以前从未见过它 此外 即使出现此错误 该程序