在下面的代碼中,我有兩個函數:func1
和gillespie
。我已將p_tot_stoch
定義爲全局變量,在func1
之內。 (將它放入函數的原因是爲了允許Numba的@jit
包裝正常工作... Numba用於代碼優化。)如何在Python中的多個函數之間共享變量,即全局?
但是,當我嘗試在代碼的最後打印p_tot_stoch時,我得到以下錯誤信息:
Traceback (most recent call last):
File "C:/Users/dis_YO_boi/Documents/Programming/Python/CodeReview.py", line 85, in <module>
p_tot_stoch = gillespie()
NameError: global name 'p_tot_stoch' is not defined
我宣佈它爲全球性的,但它看起來像的主要功能gillespie
不能訪問它。我怎樣才能解決這個問題?
我的代碼如下,謝謝你的幫助。
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from numba import jit
import math
random = np.random
DELTA = 1e-3
SIM_NUM = 100
K_MINUS = 1e-3
K_CAT = 1 - 1e-3
ZETA = 1e-4
D = 10000
QP_VEC = np.logspace(-2, 1, 101, 10)
KAPPA_M = (K_CAT + K_MINUS)/ZETA
P0_VEC = QP_VEC/DELTA
QP_DEG = np.true_divide(1000*D*QP_VEC*K_CAT,1000*QP_VEC+KAPPA_M)
@jit
def func1():
global p_tot_stoch
p_tot_stoch = np.empty((SIM_NUM, len(QP_VEC)))
@jit
def gillespie(max_time=1000):
for len_qp_ind in range(len(QP_VEC)):
qp = QP_VEC[len_qp_ind]
p0 = math.ceil(P0_VEC[len_qp_ind])
for sim_num_ind in range(SIM_NUM):
p = p0
d = D
dp = time = 0
while True:
tot = [qp, ZETA * p * d, K_MINUS * dp, K_CAT * dp]
for i in range(3):
tot[i + 1] += tot[i]
p_tot = p + dp
kt = tot[-1]
time += -np.log(1 - random.random())/kt
if time > max_time:
p_tot_stoch[sim_num_ind, len_qp_ind] = p_tot
break
event_kt = random.random() * kt
if event_kt < tot[0]:
p += 1
elif event_kt < tot[1]:
p -= 1
dp += 1
d -= 1
elif event_kt < tot[2]:
p += 1
dp -= 1
d += 1
elif event_kt < tot[3]:
dp -= 1
d += 1
return p_tot_stoch
if __name__ == '__main__':
p_tot_stoch = gillespie()
p_mean = p_tot_stoch.mean(axis=0)
p_std = p_tot_stoch.std(axis=0)
print(p_tot_stoch)