【问题标题】:Python enumerate isn't plotting the right matplotlib figures?Python enumerate 没有绘制正确的 matplotlib 数字?
【发布时间】:2020-05-19 08:54:20
【问题描述】:

我正在尝试模拟以下化学反应系统:

1S + 0T + 0U --> 0S + 0T + 0U
2S + 0T + 0U --> 0S + 1T + 0U 
0S + 1T + 0U --> 2S + 0T + 0U
0S + 1T + 0U --> 0S + 0T + 1U

反应物和产物的比例用以下数组表示:

LHS = np.array([[1, 0, 0], [2, 0, 0], [0, 1, 0], [0, 1, 0]]) <-- ratio between the reactants
RHS = np.array([[0, 0, 0], [0, 1, 0], [2, 0, 0], [0, 0, 1]]) <-- ratio between the reactants 

每个反应触发后的比率变化存储在这个数组中:

state_change_array = np.asarray(RHS - LHS)

在模拟开始时,系统中的三种反应物 S、T、U 分别具有以下离散分子数:

popul_num = np.array([1.0E5, 0, 0])

各个反应的速率存储在以下数组中:

stoch_rate = np.array([1.0, 0.002, 0.5, 0.04])

我已经编写了以下代码来模拟系统并存储计算出的popul_num的新数字

def propensity_calc(LHS, popul_num, stoch_rate):
propensity = np.zeros(len(LHS))
for row in range(len(LHS)):
        a = stoch_rate[row]     # type = numpy.float64
        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     # type = numpy.ndarray
return propensity

popul_num_all = [popul_num]
propensity = np.zeros(len(LHS))

while tao < tmax:
    propensity = propensity_calc(LHS, popul_num, stoch_rate)
    a0 = (sum(propensity))
    if a0 == 0.0:
        break
    t = np.random.exponential(1/a0)
    rxn_probability = propensity / a0   
    num_rxn = np.arange(rxn_probability.size)       
    if tao + t > tmax:
        tao = tmax
        break
    j = stats.rv_discrete(values=(num_rxn, rxn_probability)).rvs() 
    tao = tao + t
    popul_num = popul_num + np.squeeze(np.asarray(state_change_array[j]))   
    print("Population numbers:\n", popul_num)
    print("Simulation time:\n", t, tao)
    popul_num_all.append(popul_num)

popul_num_all = np.array(popul_num_all)

其中 tmax 是系统应模拟的最长时间 = 20.0,tao 是开始时间,0。

然后我得到以下内容来绘制系统中每个物种的变化数量:

for i, label in enumerate(['S', 'T', 'U']):
    plt.plot(popul_num_all[i], label=label) 
plt.legend()
plt.tight_layout()
plt.show()

代码绘图代码适用于运行的不同模拟,但在此模拟中,它显示所有三个物种都以相同的速率下降(见下图),这不是我想要的。 我玩过索引和费率,但似乎仍然无法完全正确,有什么建议吗?

顺便说一句,我已经导入了 numpy、scipy 和 matplotlib

【问题讨论】:

  • 想通了,别担心!
  • 你打算自己回答吗?

标签: python numpy matplotlib enumerate


【解决方案1】:

我的问题出在这一行:

plt.plot(popul_num_all[i], label=label)

popul_num_all 是一个大的二维数组,所以我认为问题与索引轴的两个维度有关。我必须添加:

plt.plot(popul_num_all[:, i], label=label)

使其适用于多个维度。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多