【发布时间】:2020-05-05 14:27:06
【问题描述】:
我正在尝试使用具有以下实体 Enzyme、Substrate、Enzyme-Substrate complex、Product 的简单系统在 python 3.8 中模拟蜂窝系统的 Gillespies 算法。
我有以下代码计算一系列反应的倾向函数,这些反应表示为数组的行:
propensity = np.zeros(len(LHS))
def propensity_calc(LHS, popul_num, stoch_rate):
for row in range(len(LHS)):
a = stoch_rate[row]
for i in range(len(popul_num)):
if (popul_num[i] >= LHS[row, i]):
binom_rxn = (binom(popul_num[i], LHS[row, i]))
a = a*binom_rxn
else:
a = 0
break
propensity[row] = a
return propensity.astype(float)
输入数组如下:
popul_num = np.array([200, 100, 0, 0])
LHS = np.array([[1,1,0,0], [0,0,1,0], [0,0,1,0]])
stoch_rate = np.array([0.0016, 0.0001, 0.1000])
该函数按预期工作,直到我尝试从以下 while 循环中调用它:
while tao < tmax:
propensity_calc(LHS, popul_num, stoch_rate)
a0 = sum(propensity)
if a0 <= 0:
break
else:
t = np.random.exponential(a0)
print(t)
# sample time system stays in given state from exponential distribution of the propensity sum.
if tao + t > tmax:
tao = tmax
break
j = stats.rv_discrete(name="Reaction index", values=(num_rxn, rxn_probability)).rvs() # array of reactions increasing by 1 until they get to the same length/size as rxn_probability
print(j)
tao = tao + t
popul_num = popul_num + state_change_matrix[j] # update state of system/ popul_num
while循环中的其他变量如下:
a0 = sum(propensity)
def prob_rxn_fires(propensity, a0):
prob = propensity/a0
return prob
rxn_probability = (prob_rxn_fires(propensity, a0))
num_rxn = np.arange(1, rxn_probability.size + 1).reshape(rxn_probability.shape)
当我在 while 循环中运行调用 calc_propensity 函数的代码时,它会通过 while 循环的第一次迭代并出现以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
错误首先在 calc_propensity 函数的以下行抛出:
if (popul_num[i] >= LHS[row, i]):
但由于某种原因,代码一直运行,直到它到达 calc_propensity 函数但在第二个函数调用(while 循环)中的同一行,我不明白为什么?
干杯
【问题讨论】:
-
您不应该将
len与numpy 数组一起使用,请改用myarray.shape[dimension] -
请edit您的问题并正确格式化您的代码。 Python 对缩进很敏感,目前有几个部分的语法不正确。
-
这能回答你的问题吗? Use a.any() or a.all()
-
在我看来,
popul_num和/或LHS对象并不是您想象的那样。在它崩溃的行之前打印它可以让您深入了解您实际尝试比较的内容。 -
对我来说运行正常(注释掉使用 undefined
binom的东西),您必须进行调试,从在错误之前识别问题变量开始。当在比较中使用 numpy 数组(如>=)时,会出现这样的错误。结果是一个布尔数组,不能在if语句中使用。一定有什么东西改变了该语句中被索引的数组的维度。
标签: python arrays numpy while-loop