Note: A single simulation is performed with results being saved in an HDF file.
Warning: If a results
directory exists in the working directory, old results will be lost.
In [1]:
import time
import os
import shutil
from collections import namedtuple
import numpy as np
import h5py
import pickle
import pyximport; pyximport.install()
from Iterate import iterate
In [2]:
def init_grid(c):
'''Initialized the 2D grid with random values, with an empty border.'''
Z = np.random.randint(0, 2, (c.rows, c.cols))
Z[0, :] = 0
Z[-1, :] = 0
Z[:, 0] = 0
Z[:, -1] = 0
return Z
In [3]:
# Configure parameters
Const = namedtuple('c', ['rows', 'cols', 'n_iterations', 'rootdir'])
c = Const(rows=150, cols=150, n_iterations=600, rootdir='./results/')
# Create a fresh results directory
if os.path.exists(c.rootdir):
shutil.rmtree(c.rootdir)
os.makedirs(c.rootdir)
pickle.dump(c._asdict(), open('./results/c.p', 'wb'))
In [4]:
start = time.time()
# Initialize grid
Z = init_grid(c)
Z_history = np.empty((c.rows, c.cols, c.n_iterations), dtype=int)
Z_history[:, :, 0] = Z # Initial state
for i in range(1, c.n_iterations):
Z = iterate(Z, c)
Z_history[:, :, i] = Z
print('Time elapsed: ', time.time() - start)
In [5]:
# Create new store
f = h5py.File(os.path.join(c.rootdir, 'results.hdf5'), 'w')
dset = f.create_dataset("Results", (c.rows, c.cols, c.n_iterations), dtype=int)
dset[...] = Z_history[...]
f.close()