【发布时间】:2020-09-12 00:14:31
【问题描述】:
我制作了以下课程来尝试和计时我正在运行的模拟: 编辑:
class TimeError(Exception):
"""A custom exception used to report errors in use of Timer Class"""
class simulation_timer:
def __init__(self):
self._simulation_start_time = None
self._simulation_stop_time = None
def start(self):
"""start a new timer"""
if self._simulation_start_time is not None: # attribute
raise TimeError(f"Timer is running.\n Use .stop() to stop it")
self._simulation_start_time = time.perf_counter()
def stop(self):
"""stop the time and report the elsaped time"""
if self._simulation_start_time is None:
raise TimeError(f"Timer is not running.\n Use .start() to start it.")
self._simulation_stop_time = time.perf_counter
elasped_simulation_time = self._simulation_stop_time - self._simulation_start_time <-- Error here!
self._simulation_start_time = None
print(f"Elasped time: {elasped_simulation_time:0.4f} seconds")
然后我在下面的函数中使用它:
def gillespie_tau_leaping(propensity_calc, popul_num, popul_num_all, rxn_vector, tao, delta_t, epsi):
t = simulation_timer()
t.start()
while tao < tmax:
propensity = propensity_calc(LHS, popul_num, stoch_rate)
a0 = (sum(propensity))
if a0 == 0.0:
break
# if reaction cannot fire corresponding element in rxn_vector should be zero --> tau leaping method
if popul_num.any() < 0:
break
lam = (propensity_calc(LHS, popul_num, stoch_rate)*delta_t)
rxn_vector = np.random.poisson(lam)
if tao + delta_t > tmax:
break
tao += delta_t
print("tao:\n", tao)
# divide tao by delta_t to calculate number of leaps
leap_counter = tao / delta_t # should this be after the if statement below?
if tao >= 2/a0:
for j in range(len(rxn_vector)):
state_change_lambda = np.squeeze(np.asarray(state_change_array[j])*rxn_vector[j])
popul_num = popul_num + state_change_lambda
new_propensity = propensity_calc(LHS, popul_num, stoch_rate) # maybe inside for loop?
#for m in range(len(propensity)):
for n in range(len(new_propensity)):
propensity_check = propensity + state_change_lambda
if propensity_check[n] - new_propensity[n] >= epsi*a0:
print("The value of delta_t {} choosen is too large".format(delta_t))
break
else:
popul_num = popul_num + state_change_lambda
popul_num_all.append(popul_num)
tao_all.append(tao)
#return popul_num_all.append(popul_num), tao_all.append(tao), leap_counter
else:
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("Simulation time:\n", t, tao)
t.stop()
return popul_num_all.append(popul_num), tao_all.append(tao), leap_counter
只有我不断收到以下错误:
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float'
我在这里查看了其他帖子,说这与重新定义已经内置的函数有关,所以我尝试重命名所有变量,但仍然没有运气!任何人都知道我该如何解决这个问题?
干杯
【问题讨论】:
-
哪一行报错了?
-
刚刚编辑显示在哪里
标签: python class time typeerror