In [1]:
%pylab
In [2]:
mpl.rcParams.update({'font.family': 'serif',
'font.size': 12,
'font.sans-serif': [],})
In [3]:
import sys
from collections import defaultdict
from imp import reload
import numpy.fft as fft
from mpl_toolkits.mplot3d import Axes3D
from scipy import optimize
#import prettyplotlib
import ssad
import ensemble as we
In [4]:
reload(ssad)
reload(we)
from ssad import Reaction, Trajectory
In [5]:
# From http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Progress%20Bars.ipynb
class ProgressBar:
def __init__(self, iterations):
self.iterations = iterations
self.prog_bar = '[]'
self.fill_char = '='
self.width = 50
self.__update_amount(0)
def animate(self, iter):
print('\r', self, end='')
sys.stdout.flush()
self.update_iteration(iter + 1)
def update_iteration(self, elapsed_iter):
self.__update_amount((elapsed_iter / float(self.iterations)) * 100.0)
self.prog_bar += ' %d of %s complete' % (elapsed_iter, self.iterations)
def __update_amount(self, new_amount):
percent_done = int(round((new_amount / 100.0) * 100.0))
all_full = self.width - 2
num_hashes = int(round((percent_done / 100.0) * all_full))
self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
pct_place = (len(self.prog_bar) // 2) - len(str(percent_done))
pct_string = '%d%%' % percent_done
self.prog_bar = self.prog_bar[0:pct_place] + \
(pct_string + self.prog_bar[pct_place + len(pct_string):])
def __str__(self):
return str(self.prog_bar)
In [93]:
species = ['X']
In [12]:
A = 100.0
B = 4.5
C = 5.0
tau = 1.0
rxns = [Reaction([0], [+1], A),
Reaction([1], [-1], B),
Reaction([1], [-1], C, delay=tau)]
In [26]:
# Calculate the expected equilibrium value
A / (B + C)
Out[26]:
Compute the Hopf bifurcation point in the Langevin limit. Tentatively bracket to the first minimum of the cosine function,
In [13]:
ubound = np.sqrt((np.pi / tau)**2 + B**2)
bif_root = lambda C: np.cos(tau * np.sqrt(C**2 - B**2)) + B / C
C_bif = optimize.brentq(bif_root, B, ubound)
In [14]:
C_bif
Out[14]:
In [21]:
C_range = np.linspace(B, ubound, 1000)
plot(C_range, bif_root(C_range))
Out[21]:
In [14]:
plot(C_range, -B / C_range)
plot(C_range, np.cos(tau * np.sqrt(C_range**2 - B**2)))
Out[14]:
In [95]:
# The starting state can be chosen either to induce oscillations or to remain at equilibrium.
trj = Trajectory([0], rxns)
In [96]:
trj.run_dynamics(120)
In [29]:
trj.run_dynamics(duration=None, stop_time=820.0)
In [97]:
times = asarray(trj.hist_times)
states = asarray(trj.hist_states)
plot(times, states[:,0])
Out[97]:
In [98]:
init_trjs = []
init_trjs_zero = []
ntrajs = 40
nbins = 30
binrange = (0, 60)
bin_xs, bin_width = np.linspace(*binrange, num=nbins, endpoint=False, retstep=True)
paving = we.UniformPaving(*binrange, bin_counts=nbins)
for idx in range(ntrajs):
init_state = random.randint(*binrange)
init_time = random.random_sample() * rxns[2].delay
init_trjs.append(we.WeightedTrajectory([init_state], rxns, 1.0 / ntrajs, init_time=init_time))
init_trjs_zero.append(we.WeightedTrajectory([0], rxns, 1.0 / ntrajs, init_time=init_time))
In [99]:
print([trj.state for trj in init_trjs])
In [33]:
we_test = we.Ensemble(10, paving, (10, 10), init_trjs)
niter_test = 5
pbar = ProgressBar(niter_test)
pbar.animate(0)
for stidx in range(niter_test):
we_test.run_step()
pbar.animate(stidx + 1)
In [93]:
plot_trjs = list(we_test)
sample_step = int(len(plot_trjs) / 7)
plot_trjs = plot_trjs[::sample_step]
fig = figure()
ax = fig.gca()
for trj in plot_trjs:
trj_times = np.array(trj.hist_times)
trj_states = np.array(trj.hist_states)
prettyplotlib.plot(trj_times, trj_states[:,0], axes=ax)
In [100]:
step_time = 2.0
run_time = 60.0
niter = int(run_time / step_time)
we_res = we.Ensemble(step_time, paving, (4, 4), init_trjs_zero)
we_nores = we.Ensemble(step_time, paving, (4, 4), init_trjs_zero)
In [101]:
pbar = ProgressBar(niter)
pdist_res = np.empty((nbins, niter))
In [102]:
pbar.animate(0)
for stidx in range(niter):
we_res.run_step(prune=False)
pdist_res[:,stidx] = we_res.get_pdist()
pbar.animate(stidx + 1)
Let's plot some sample trajectories, to make sure the phases are suffiently randomized:
In [107]:
plot_trjs = list(we_res)
sample_step = int(len(plot_trjs) / 5)
plot_trjs = plot_trjs[::sample_step]
fig = figure()
ax = fig.gca()
for trj in plot_trjs:
trj_times = np.array(trj.hist_times)
trj_states = np.array(trj.hist_states)
plot(trj_times, trj_states[:,0], axes=ax)
In [56]:
def plot_trj(trj):
times = np.array(trj.hist_times)
states = np.array(trj.hist_states)
plot(times, states[:,0])
In [58]:
plot_trj(plot_trjs[2])
In [59]:
pdist_res = we_res.get_pdist()
bar(bin_xs, pdist_res)
Out[59]:
In [60]:
we_res.get_bin_counts()
Out[60]:
In [104]:
pbar = ProgressBar(niter)
pdist_nores = np.empty((nbins, niter))
In [105]:
pbar.animate(0)
for stidx in range(niter):
we_nores.run_step(prune=False, resample=False)
pbar.animate(stidx + 1)
In [112]:
we_nores._recompute_bins()
we_nores._resample()
In [113]:
for stidx in range(10):
we_nores.run_step(prune=False, resample=False)
As before, make sure the phases are suffiently randomized:
In [114]:
plot_trjs = list(we_nores)
plot_trjs = plot_trjs[::8]
fig = figure()
ax = fig.gca()
for trj in plot_trjs:
trj_times = np.array(trj.hist_times)
trj_states = np.array(trj.hist_states)
plot(trj_times, trj_states[:,0], axes=ax)
In [70]:
plot(trj_times, trj_states[:,0])
Out[70]:
In [115]:
plot_trj(plot_trjs[-1])
In [116]:
plot_trjs[-1].sample_state(50.0)
Out[116]:
In [90]:
plot_trjs[-1].init_time
Out[90]:
In [85]:
test_trj = plot_trjs[-2]
test_trj.time - tau
Out[85]:
In [86]:
test_trj.sample_state(test_trj.time - tau)
Out[86]:
In [80]:
test_trj.run_dynamics(10)
In [88]:
plot_trj(test_trj)
In [16]:
step_time = 2.0
niter = 30
run_time = step_time * niter
nens = 30
wes_res = []
wes_nores = []
for eidx in range(nens):
wes_res.append(we.Ensemble(step_time, paving, (2, 2), init_trjs))
wes_nores.append(we.Ensemble(step_time, paving, (2, 2), init_trjs))
In [17]:
prog_ctr = 0
pbar = ProgressBar(nens * niter * 2)
In [18]:
pbar.animate(0)
for stidx in range(niter):
for ens in wes_res:
ens.run_step(resample=True)
prog_ctr += 1
pbar.animate(prog_ctr)
for ens in wes_nores:
ens.run_step(resample=False)
prog_ctr += 1
pbar.animate(prog_ctr)
In [37]:
ens_pdist_res = np.vstack(ens.get_pdist() for ens in wes_res)
ens_pdist_nores = np.vstack(ens.get_pdist() for ens in wes_nores)
In [21]:
sum(len(ens) for ens in wes_res)
Out[21]:
In [24]:
sum(len(trj.hist_states) for trj in wes_res[0])
Out[24]:
In [38]:
np.savez('../results/del_deg_ens_of_ens.npz', pdist_res=ens_pdist_res, pdist_nores=ens_pdist_nores)
In [39]:
ens_pdist_res.shape
Out[39]:
In [40]:
ens_pdist_res_avg = np.average(ens_pdist_res, axis=0)
ens_pdist_nores_avg = np.average(ens_pdist_nores, axis=0)
ens_pdist_res_sdm = np.std(ens_pdist_res, axis=0) / sqrt(nens)
ens_pdist_nores_sdm = np.std(ens_pdist_nores, axis=0) / sqrt(nens)
In [43]:
fig = figure()
ax = fig.gca()
ax.bar(bin_xs, ens_pdist_nores_avg, yerr=ens_pdist_nores_sdm, alpha=0.6, color='red', ecolor='red', label='Without Resampling')
ax.bar(bin_xs, ens_pdist_res_avg, yerr=ens_pdist_res_sdm, alpha=0.6, color='blue', ecolor='blue', label='With Resampling')
ax.legend(loc='best')
ax.set_ylim(bottom=0.0)
ax.set_xlabel('Number of X')
ax.set_ylabel('Probability Density (per bin)')
Out[43]:
In [44]:
fig.savefig('../results/delayed-deg-pdist.pgf')
In [45]:
chis = (ens_pdist_res_avg - ens_pdist_nores_avg) / np.sqrt(ens_pdist_nores_sdm**2 + ens_pdist_res_sdm**2)
chis[np.abs(chis) > 1E9] = np.nan
In [52]:
fig = figure()
ax = fig.gca()
ax.bar(bin_xs, chis)
ax.set_xlabel('Number of X')
ax.set_ylabel(r'Normalized Difference (Wtd - UnWtd)')
ax.axhline(0, color='black')
ax.grid()
In [53]:
fig.savefig('../results/delayed-deg-chi.pgf')
In [15]:
n_samples = 2**11
max_freq_num = int(n_samples / 2)
In [16]:
s_times = np.linspace(0, 200, n_samples)
s_states = trj.sample_state_seq(s_times)
In [17]:
amp_spec = fft.rfft(s_states, axis=1)
freqs = fft.fftfreq(s_times.size, d=(s_times[-1] - s_times[0])/n_samples)
In [18]:
plot(freqs[:max_freq_num], np.abs(amp_spec[0,:-1])**2)
Out[18]:
In [ ]: