繁体   English   中英

为什么我的 function 第二次从 python while 循环中调用时崩溃?

[英]Why does my function crash the second time it's called from within a python while loop?

我正在尝试使用具有以下实体酶、底物、酶-底物复合物、产品的简单系统来模拟 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)

输入arrays如下:

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

function 按预期工作,直到我尝试从以下 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 function 的代码时,它会通过 while 循环的第一次迭代并出现以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

错误首先在 calc_propensity function 的以下行中引发:

if (popul_num[i] >= LHS[row, i]):

但由于某种原因,代码一直运行,直到它到达 calc_propensity function 但在第二个 function 调用(while 循环)中的同一行,我不明白为什么?

干杯

看来 if 语句中的值首先不应该在 if 条件中使用。 您应该使用 .any() 或 .all() 函数。 这是一个链接来说明 ValueError 代表什么:

https://sopython.com/canon/119/the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM