【发布时间】:2020-07-10 13:44:07
【问题描述】:
我创建了两个程序来对化学反应系统进行随机模拟。在程序中,我有一个函数,该函数旨在使用不断变化的分子数popul_num 的derivative 和每个反应的随机速率常数stoch_rate 更新数组的元素@ 在第一个程序中,函数看起来像如下:
popul_num = np.array([1.0E9, 0, 0])
stoch_rate = np.array([1.0, 0.002, 0.5, 0.04])
def update_array(popul_num, stoch_rate):
"""Specific to this model
will need to change if different model
implements equaiton 24 of the Gillespie paper"""
# calcualte in seperate varaible then pass it into the array
s_derviative = stoch_rate[1]*(2*popul_num[0] -1)/2
b = np.array([[1.0, 0.0, 0.0], [s_derviative, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.4, 0.0]])
return b
此函数返回b,它是shape(4, 3) 的array
在下一个程序中,我添加了更多的反应和更多的反应物,功能如下:
popul_num = np.array([1.0E5, 3.0E5, 0.0, 1.0E5, 0.0, 0.0, 0.0, 0.0])
stoch_rate = np.array([0.015, 0.00016, 0.5, 0.002, 0.002, 0.8])
def update_array(popul_num, stoch_rate):
"""Specific to this model
will need to change if different model
implements equaiton 24 of the Gillespie paper"""
s_derivative = stoch_rate[0]*popul_num[1]*((popul_num[1] - 1)/2) # derivative with respect to S is a function of X
x_derivative = stoch_rate[0]*popul_num[0]*((2*popul_num[1] - 1)/2) # derivative with respect to X is a function of S
r_derivative = stoch_rate[1]*((popul_num[3]*(popul_num[3]))/2)
r2_derivative = stoch_rate[2]*popul_num[4] # derivative with respect to R is a function of Y type = numpy.float64
y_derivative = stoch_rate[3]*popul_num[3] # derivative with respect to Y is a function of R type = numpy.float64
x2_derivative = stoch_rate[4]*((popul_num[1] - 1)/2)
b = np.array([[x_derivative, s_derivative, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0,
r_derivative, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, r2_derivative, y_derivative, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, stoch_rate[3], 0.0, 0.0, 0.0, 0.0], [x2_derivative, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, stoch_rate[5], 0.0]])
b.reshape((6,8))
print("Shape b:\n", b.shape)
return b
只有这会返回shape(6,) 的array,我需要它是shape(6, 8) 的二维数组我尝试使用reshape() 方法,但这会导致以下错误:
ValueError: cannot reshape array of size 6 into shape (6,8)
在我调用reshape() 命令的那一行被抛出
我不明白第二个函数有什么不同意味着它不返回二维数组?
干杯
【问题讨论】:
-
代码太多了!请告诉我们该行并在可能的情况下突出显示 ValueError 发生的位置。
-
编辑了代码以添加
reshape调用。我真的不明白为什么我必须首先调用它以及为什么array不是自动二维的。
标签: python arrays reshape numpy-ndarray