我的代码是供用户创建应用于起始状态的自定义矩阵。因为我希望它能够生成用户希望的任何方形矩阵,所以我必须做一些时髦的事情。我的基本方法是让用户输入不同的元素,这些元素都放在一个列表中。根据列表中元素的位置,它们会被放入不同的行中。我使用numpy.append()
执行此操作。但是,它给出了错误
Traceback (most recent call last):
File "/home/physicsnerd/Documents/Quantum-Computer-Simulator/tests.py", line 39, in <module>
customop(qstat)
File "/home/physicsnerd/Documents/Quantum-Computer-Simulator/tests.py", line 21, in customop
np.append(matrix,current_row,axis=0)
File "/usr/lib/python3/dist-packages/numpy/lib/function_base.py", line 4575, in append
return concatenate((arr, values), axis=axis)
ValueError: all the input arrays must have same number of dimensions
回复我的.append()
行。我做错了什么?
要在此特定代码情况下重现错误,请键入&#34; 2&#34;,输入&#34; 0&#34;,输入,&#34; 1&#34;,输入,&#34 ; 1&#34;,输入,&#34; 0&#34 ;,输入,尽管这似乎打破了最后四个中的任何数字。另一个注意事项 - print(current_row)
行用于调试参考。与print(matrix)
行相同。
import numpy as np
import math
def customop(qstat):
dimensions = float(input("What are the dimensions of your (square) matrix? Please input a single number: "))
iterator = 1
iterator_2 = 1
elements = []
while iterator <= dimensions:
while iterator_2 <= dimensions:
elements.append(float(input("Matrix element at "+str(iterator)+","+str(iterator_2)+": ")))
iterator_2+=1
iterator_2 = 1
iterator+=1
matrix = np.matrix([])
element_places = list(range(len(elements)))
current_row = []
for i in element_places:
print(i%dimensions)
if i%dimensions == 0 and i > 0:#does this work? column vs row, elements, etc
np.append(matrix,current_row,axis=0)
current_row = []
current_row.append(elements[i])
elif i == 0:
current_row.append(elements[i])
print(current_row)
else:
current_row.append(elements[i])
print(current_row)
if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(2)) == True:
print(matrix)
return np.dot(matrix, qstat)
else:
print(matrix)
print("matrix not unitary, pretending no gate was applied")
return qstat
qstat = np.matrix([[0],[1]])
customop(qstat)
答案 0 :(得分:3)
鉴于您在上面指定的输入(大小2和元素0,1,1,0),错误来自于您尝试将一行2个元素追加到空矩阵的事实。您的(空)矩阵具有形状(1,0),而current_row具有形状(2,),如果变成np.array。
正如上面提到的DYZ,您已经知道了矩阵的尺寸,因此您可以将输入重新整形为方形矩阵,如下所示
np.matrix(elements).reshape((int(dimensions), int(dimensions)))
由于您要求元素的顺序与重塑函数的默认方式一致,因此您无需添加任何其他内容。注意我必须转换为上面的整数,因为您将维度解析为浮点数。
如此简化,您的代码将如下所示:
# matrix.py
import numpy as np
import math
def customop(qstat):
dimensions = int(input("What are the dimensions of your (square) matrix? Please input a single number: "))
iterator = 1
iterator_2 = 1
elements = []
while iterator <= dimensions:
while iterator_2 <= dimensions:
elements.append(float(input("Matrix element at "+str(iterator)+","+str(iterator_2)+": ")))
iterator_2+=1
iterator_2 = 1
iterator+=1
matrix = np.matrix(elements).reshape(dimensions, dimensions)
if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(2)) == True:
print(matrix)
return np.dot(matrix, qstat)
else:
print(matrix)
print("matrix not unitary, pretending no gate was applied")
return qstat
qstat = np.matrix([[0],[1]])
customop(qstat)
$ python3 matrix.py
What are the dimensions of your (square) matrix? Please input a single number: 3
Matrix element at 1,1: 1
Matrix element at 1,2: 2
Matrix element at 1,3: 3
Matrix element at 2,1: 1
Matrix element at 2,2: 2
Matrix element at 2,3: 3
Matrix element at 3,1: 1
Matrix element at 3,2: 2
Matrix element at 3,3: 3
[[ 1. 2. 3.]
[ 1. 2. 3.]
[ 1. 2. 3.]]
如果您知道矩阵将是正方形,那么您可以推断尺寸将是输入元素数量的平方根
dimensions = math.sqrt(len(elements))
请注意,这可能会使错误处理变得复杂并影响UX。
您可以用来查看正在发生的事情的有用工具是ipdb。我放弃了这条线
import ipdb; ipdb.set_trace()
就在你原来的np.append行之前,这就是帮助我突出你的错误的原因。
答案 1 :(得分:3)
如果我理解正确,确定矩阵维度,附加用户的值,然后调整列表大小并将其转换为矩阵应该有效:
dimension = int(输入(“你的(方形)矩阵的尺寸是多少?请输入一个数字:”))
ls = []
for y in range(dimension):
for x in range(dimension):
ls.append(float(input('What value for position ({}, {}): '.format(y+1, x+1))))
np.matrix(np.resize(ls, (dimension, dimension)))
输出:
What are the dimensions of your (square) matrix? Please input a single number: 3
What value for position (1, 1): 1
What value for position (1, 2): 2
What value for position (1, 3): 3
What value for position (2, 1): 1
What value for position (2, 2): 2
What value for position (2, 3): 3
What value for position (3, 1): 1
What value for position (3, 2): 2
What value for position (3, 3): 3
Out[29]:
matrix([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
答案 2 :(得分:1)
其他人已经指出了为什么你的方法会让你犯这个错误。我只是添加另一种可以创建矩阵的方法。请注意,在您要求输入之前,您将获得用户的尺寸(并且它始终是方形矩阵)。因此,你可以创建一个零矩阵,然后随着用户给你的条目填写它,如下所示:
def customop(qstat):
dimensions = input("What are the dimensions of your (square) matrix? Please input a single number: ")
matrix = np.zeros([dimensions, dimensions])
for iterator in range(dimensions):
for iterator_2 in range(dimensions):
matrix[iterator, iterator_2] = float(input("Matrix element at "+str(iterator)+","+str(iterator_2)+": "))
if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(2)) == True:
print(matrix)
return np.dot(matrix, qstat)
else:
print(matrix)
print("matrix not unitary, pretending no gate was applied")
return qstat
qstat = np.matrix([[0],[1]])
customop(qstat)
我用for循环替换了while循环,以便自动处理初始化和递增。
答案 3 :(得分:0)
好的,所以这里有一些不同的事情,其中一些已被处理,其中一些没有。
正如@DYZ指出的那样,第一件事就是你试图将行向量附加到空矩阵。这可以通过重塑空矩阵来解决。
代码也可以大大简化为:
import numpy as np
def custom_operator(state):
dimension = int(input("What are the dimensions of your (square) matrix? Please input a single number:"))
elements = list()
for x in range(dimension):
for y in range(dimension):
value = float(input("Matrix element at ({x}, {y}):".format(x=x+1, y=y+1)))
elements.append(value)
operator = np.matrix(np.resize(elements, (dimension, dimension)))
output_state = np.dot(operator, state)
return output_state
state = np.matrix([[0], [1]])
custom_operator(state)
请注意,我已删除了您未使用的import math
语句,并且当您要求维度时,您应该将响应转换为int
而非浮动。< / p>
也没有必要检查门是否是单一的。无论哪种方式,您仍然返回状态操作的输出。 (除非你真的想知道它是不是。)如果你确实想要,如果尺寸不是2,你当前的检查将失败。更好的检查将是
np.allclose(operator.dot(operator.T.conj()), np.eye(len(dimension)))
但是,考虑到你想对你的状态应用任何门,你知道矩阵的尺寸必须是什么。允许用户指定他们想要将qutrit门应用于量子位状态只会允许他们引入错误。因此,更好的代码版本将是:
import numpy as np
def custom_operator(input_state):
dimension, width = input_state.shape
if width != 1:
error_message = "Input state must be a column vector"
raise ValueError(error_message)
elements = list()
for x in range(dimension):
for y in range(dimension):
value = float(input("Matrix element at ({x}, {y}):".format(x=x+1, y=y+1)))
elements.append(value)
operator = np.matrix(np.resize(elements, (dimension, dimension)))
output_state = np.dot(operator, input_state)
return output_state
state = np.matrix([[0], [1]])
custom_operator(state)