def test_serialization(): rd = load(JSON_PATH) assert rd.n == 3 assert rd.stoich_active == [[0, 1]] assert rd.stoich_prod == [[2]] assert list(rd.k) == [0.3] assert rd.D.tolist() == [0.1, 0.2, 0.3]
def test_chemistry(): sbstncs = mk_sn_dict_from_names('ABC', D=[.1, .2, .3]) r1 = Reaction({'A': 1, 'B': 1}, {'C': 1}, 0.3) rsys = ReactionSystem([r1], sbstncs) rd = ReactionDiffusion.from_ReactionSystem(rsys) serialized_rd = load(JSON_PATH) assert rd.stoich_active == serialized_rd.stoich_active assert rd.stoich_prod == serialized_rd.stoich_prod assert rd.stoich_inact == serialized_rd.stoich_inact assert np.allclose(rd.k, serialized_rd.k) assert np.allclose(rd.D, serialized_rd.D)
def test_f(log): logy, logt, use_log2 = log N = 1 rd = load(JSON_PATH, N=N, logy=logy, logt=logt, use_log2=use_log2) y0 = np.array(C0) t0 = 42.0 ref_f = _get_ref_f(rd, t0, y0, logy, logt, use_log2=use_log2) fout = rd.alloc_fout() y = rd.logb(y0) if logy else y0 t = rd.logb(t0) if logt else t0 rd.f(t, y, fout) assert np.allclose(fout, ref_f)
def test_dump_load(): rd1 = ReactionDiffusion(2, [[0]], [[1]], [1]) f = tempfile.NamedTemporaryFile(delete=False) try: f.close() dump(rd1, f.name) rd2 = load(f.name) assert rd1.n == rd2.n assert rd1.k == rd2.k assert rd1.stoich_active == rd2.stoich_active assert rd1.stoich_prod == rd2.stoich_prod finally: os.unlink(f.name)
def main(tend=3.0, N=30, nt=30, plot=False, logy=False, logt=False, savefig='None', verbose=False): def mod1(x): return x/(x**2+1) # decay A->B is modulated with x rd = load( os.path.join(os.path.dirname( __file__), 'four_species.json'), N=N, modulation=[[mod1(x/3+0.1) for x in range(N)]], modulated_rxns=[1], logt=logt, logy=logy) y0 = np.array([1.3, 1e-4, 0.7, 1e-4]) # y0 = np.concatenate([y0/(i+1)*(0.25*i**2+1) for i in range(N)]) y0 = np.concatenate([y0 for i in range(N)]) t0 = 1e-10 tout = np.linspace(t0, tend, nt) integr = run(rd, y0, tout) if verbose: pprint(integr.info) cx = rd.x[:-1]+np.diff(rd.x)/2 # center x if plot: # Using matplotlib for 3D plots: from mpl_toolkits.mplot3d import Axes3D assert Axes3D # silence pyflakes from matplotlib import cm from matplotlib import pyplot as plt from chemreac.util.plotting import save_and_or_show_plot fig = plt.figure() for i, l in enumerate('ABCD'): ax = fig.add_subplot(3, 2, i+1, projection='3d') T, X = np.meshgrid(cx, tout) ax.plot_surface(T, X, integr.Cout[:, :, i], rstride=1, cstride=1, cmap=cm.YlGnBu_r) ax.set_xlabel('x / m') ax.set_ylabel('time / s') ax.set_zlabel(r'C / mol*m**-3') ax.set_title(l) ax.legend(loc='best') ax = fig.add_subplot(3, 2, 5) print(np.array(rd.modulation).shape) ax.plot(cx, np.array(rd.modulation)[0, :]) save_and_or_show_plot(savefig=savefig)
def test_dense_jac_cmaj(log): logy, logt, use_log2 = log N = 1 rd = load(JSON_PATH, N=N, logy=logy, logt=logt, use_log2=use_log2) y0 = np.array(C0) t0 = 42.0 ref_J = _get_ref_J(rd, t0, y0, logy, logt, order='F', use_log2=use_log2) Jout = np.empty_like(ref_J) y = rd.logb(y0) if logy else y0 t = rd.logb(t0) if logt else t0 rd.dense_jac_cmaj(t, y, Jout) assert np.allclose(Jout, ref_J)
def _test_integrate(params): logy, logt, N, geom, use_log2 = params rd = load(JSON_PATH, N=N, logy=logy, logt=logt, geom=geom, use_log2=use_log2) assert rd.geom == geom y0 = np.array(C0*N) ref = np.genfromtxt(BLESSED_PATH) ref_t = ref[:, 0] ref_y = ref[:, 1:rd.n+1] t0 = 3.0 tend = 5.0+t0 nt = 137 tout = np.linspace(t0, tend, nt+1) assert np.allclose(tout-t0, ref_t) _test_f_and_dense_jac_rmaj(rd, t0, rd.logb(y0) if logy else y0) integr = run(rd, y0, tout, with_jacobian=True) for i in range(N): assert np.allclose(integr.Cout[:, i, :], ref_y, atol=1e-4)
def integrate_rd(t0=1e-7, tend=.1, doserate=15, N=1000, nt=512, nstencil=3, logy=False, logt=False, num_jacobian=False, savefig='None', verbose=False, plot=False, plot_jacobians=False): null_conc = 1e-24 mu = 1.0 # linear attenuation rho = 1.0 # kg/dm3 rd = load(os.path.join(os.path.dirname(__file__), 'aqueous_radiolysis.json'), ReactionDiffusion, N=N, logy=logy, logt=logt, bin_k_factor=[[doserate * rho * exp(-mu * i / N)] for i in range(N)], nstencil=nstencil) y0_by_name = json.load( open( os.path.join(os.path.dirname(__file__), 'aqueous_radiolysis.y0.json'), 'rt')) # y0 with a H2 gradient y0 = np.array([[ y0_by_name.get(k, null_conc) if k != 'H2' else 1e-3 / (i + 2) for k in rd.substance_names ] for i in range(rd.N)]) tout = np.logspace(log(t0), log(tend), nt + 1, base=e) integr = run(rd, y0, tout, with_jacobian=(not num_jacobian))
def integrate_rd(tend=10.0, N=1, nt=500, jac_spy=False, linear_solver='default', logy=False, logt=False, plot=False, savefig='None', verbose=False, graph=False, **kwargs): """ Integrates the reaction system defined by :download:`four_species.json <examples/four_species.json>` """ rd = load(os.path.join(os.path.dirname( __file__), 'four_species.json'), N=N, x=N, logy=logy, logt=logt) y0 = np.array([1.3, 1e-4, 0.7, 1e-4]) y0 = np.concatenate([y0/(i+1)*(0.25*i**2+1) for i in range(N)]) t0 = 1e-10 if linear_solver == 'default': if rd.N == 1: linear_solver = 'dense' elif rd.N > 1: linear_solver = 'banded' if linear_solver not in ('dense', 'banded'): raise NotImplementedError("dense or banded linear_solver") import matplotlib.pyplot as plt if jac_spy: fout = np.empty(rd.n*rd.N) rd.f(t0, y0, fout) print(fout) if linear_solver == 'dense': jout = np.zeros((rd.n*rd.N, rd.n*rd.N), order='F') rd.dense_jac_cmaj(t0, y0, jout) coloured_spy(np.log(np.abs(jout))) elif linear_solver == 'banded': # note rd.n*3 needed in call from scipy.integrate.ode jout = np.zeros((rd.n*2+1, rd.n*rd.N), order='F') rd.banded_packed_jac_cmaj(t0, y0, jout) coloured_spy(np.log(np.abs(jout))) print(jout) plt.show() else: tout = np.linspace(t0, tend, nt) integr = run(rd, y0, tout, **kwargs) if verbose: print(integr.info) if plot: plt.figure(figsize=(6, 4)) for i, l in enumerate('ABCD'): plt.plot(integr.tout, integr.Cout[:, 0, i], label=l) plt.title("Time evolution of concentrations") plt.legend() save_and_or_show_plot(savefig=savefig) plt.figure(figsize=(6, 10)) plot_jacobian( rd, np.log(integr.tout) if rd.logt else integr.tout, np.log(integr.Cout) if rd.logy else integr.Cout, 'ABCD', lintreshy=1e-10 ) plt.tight_layout() if savefig != 'None': base, ext = os.path.splitext(savefig) savefig = base + '_jacobian' + ext save_and_or_show_plot(savefig=savefig) plt.figure(figsize=(6, 10)) plot_per_reaction_contribution( integr, 'ABCD' ) plt.tight_layout() if savefig != 'None': savefig = base + '_per_reaction' + ext save_and_or_show_plot(savefig=savefig) if graph: print(rsys2graph(ReactionSystem.from_ReactionDiffusion(rd, 'ABCD'), 'four_species_graph.png', save='.')) return integr