我有一些代码可以在一定数量的时间点上运行模拟,并重复该过程一定次数。为了保存数据,我使用在第10-11行中创建的h5py数据集。我在for循环中运行了一定次数的计算,然后将其写入h5py文件。在time_points = np.arange(10**1)
和n_simulations = 10**1
的计算机上,这似乎工作正常。在第23行中,gillespie_ssa是另一个函数,该函数产生一个数组作为输出并将其写入h5py文件中的适当位置。
def prod_out(k):
args = np.array(k)
time_points = np.arange(10**1)
n_simulations = 10**1 # no. of simulsations
nch = k[2]
fval = int(k[0]/k[1])
with h5py.File("./pops%d.hdf5" %fval, "a") as locals()['hdf5_store_{}'.format(fval)]:
locals()['pops_{}'.format(fval)] = locals()['hdf5_store_{}'.format(fval)].require_dataset('pops_{}'.format(fval),(n_simulations, len(time_points),2), dtype='int8' ,compression="gzip", chunks=True)
# Run the calculations
#locals()['hdf5_store_{}'.format(fval)]= h5py.File("./pops%d.hdf5" %fval, "a")
#locals()['pops_{}'.format(fval)] = locals()['hdf5_store_{}'.format(fval)].require_dataset('pops_{}'.format(fval),(n_simulations, len(time_points),2), dtype='int8' ,compression="gzip", chunks=True)
# Run the calculations
for i in range(n_simulations):
x=np.random.randint(0,k[2]) #start each simulation from random initial condition
population_0 = np.array([x, k[2]-x])
with h5py.File("./pops%d.hdf5" %fval, "a") as locals()['hdf5_store_{}'.format(fval)]:
locals()['pops_{}'.format(fval)] = locals()['hdf5_store_{}'.format(fval)].require_dataset('pops_{}'.format(fval),(n_simulations, len(time_points),2), dtype='int8' ,compression="gzip", chunks=True)
locals()['pops_{}'.format(fval)][i,:,:]=(gillespie_ssa(propensity, update,
population_0, time_points, fval ,args=args))
return locals()['hdf5_store_{}'.format(fval)].close()
然后我在大学的群集time_points = np.arange(10**12)
和n_simulations = 10**3
上运行它,但是,我的工作超时了,由于该程序被中断,因此当我尝试读取它们时产生的文件给出以下错误:
OSError: Unable to open file (truncated file: eof = 96, sblock->base_addr = 0, stored_eof = 2048)
我相信这是由于hdf5文件关闭不当导致的?我认为注释掉第14行和第15行,并使用with
语句可以解决此问题,但是,当我中断工作时,在测试用例中仍然遇到相同的错误。 (如果我允许它正确完成,它将产生输出)。 with
语句是否需要.flush()
的显式.close()
;这是我所缺少的吗?
使用h5py文件进行读写的安全方法是什么,即使出现中断,也要确保文件中仍然有可用数据?
您可以将工作分成较小的部分,将每个部分保存到一个不同的文件中,最后,最后将文件合并为一个大文件。
运行脚本时,您必须检查哪些部分已经完成,然后跳过再次执行,那么最终您将完成操作。
并回答您的问题:不,在程序终止时hdf5文件不会安全保存,您必须自行正确关闭它们。