r"""Solves the heat equation in 1D using a discrete PINN. .. math:: \partial_t u - \partial_{xx} u & = f in \Omega \times (0, T) \\ \partial_x u & = g on \partial \Omega \times (0, T) \\ u & = u_0 on \Omega \times {0} where :math:`u: \partial \Omega \times (0, T) \to \mathbb{R}` is the unknown function, :math:`\Omega \subset \mathbb{R}` is the spatial domain and :math:`(0, T) \subset \mathbb{R}` is the time domain. The equation is solved on a segment domain; strong (homogeneous Dirichlet) boundary conditions and natural gradient preconditioning are used. The equation is discretized in time using: - an explicit Euler method, where the Laplacian is treated as an explicit operator, and - an implicit Euler method, where the Laplacian is treated as an implicit operator. """ import jax import jax.numpy as jnp import matplotlib.pyplot as plt from scimba_jax.domains.meshless_domains.domains_1d import Segment1D from scimba_jax.linear_approximation.time_integrators.butcher_tableau import ( build_explicit_euler_tableau, build_implicit_euler_tableau, ) from scimba_jax.nonlinear_approximation.approximation_spaces.approximation_spaces import ( ApproximationSpace, ) from scimba_jax.nonlinear_approximation.integration.monte_carlo import ( DomainSampler, TensorizedSampler, ) from scimba_jax.nonlinear_approximation.networks.mlp import MLP from scimba_jax.nonlinear_approximation.numerical_solvers.discrete_pinns import ( DiscretePINN, ) from scimba_jax.physical_models.temporal_pde.heat_equations import SemiDiscreteHeatND from scimba_jax.plots.plots_nd import plot_abstract_approx_spaces N_COLLOC = 900 N_BC_COLLOC = 2000 N_EPOCHS_INIT = 100 N_EPOCHS = 10 DOM_X = Segment1D((0.0, 1.0), is_main_domain=True) DOM_T = (0.0, 0.2) SAMPLER = TensorizedSampler([DomainSampler(DOM_X)], model_type="x") def exact_sol(t: jnp.ndarray, x: jnp.ndarray) -> jnp.ndarray: return jnp.exp(-(t * jnp.pi**2)) * jnp.sin(jnp.pi * x) def f_init(x: jnp.ndarray) -> jnp.ndarray: t = jnp.zeros_like(x) return exact_sol(t, x) def post_processing(approx: jnp.ndarray, x: jnp.ndarray) -> jnp.ndarray: return approx * x * (1.0 - x) # create the discrete PINN parameters pde = SemiDiscreteHeatND(main_domain=DOM_X, time_domain=DOM_T, bc="strong") params = { "explicit euler": { "tableau": build_explicit_euler_tableau(), "explicit_pde": pde, "implicit_pde": None, }, "implicit euler": { "tableau": build_implicit_euler_tableau(), "explicit_pde": None, "implicit_pde": pde, }, } nt = 15 in_size = 1 out_size = 1 space = None spaces = [] errors_over_time = [] for method, param in params.items(): butcher_tableau = param["tableau"] explicit_pde = param["explicit_pde"] implicit_pde = param["implicit_pde"] key = jax.random.PRNGKey(0) discrete_pinn = DiscretePINN( DOM_X, DOM_T, SAMPLER, out_size, nt, butcher_tableau, explicit_pde, implicit_pde, exact_solution=exact_sol, ) if space is None: # train the initial condition only for the first tableau nn = MLP(in_size=in_size, out_size=out_size, hidden_sizes=[12] * 2, key=key) space = ApproximationSpace( {"x": 1}, [(nn, "scalar", None)], model_type="x", post_processing=post_processing, ) print("Initializing the discrete PINN...") key, space = discrete_pinn.initialize( key, space, f_init, N_EPOCHS_INIT, N_COLLOC ) print("Initializing the discrete PINN... Done\n") plot_abstract_approx_spaces( [space], DOM_X, solution=f_init, error=f_init, title="initial condition" ) print(f"\nSolving with the {method} method...") key, space_ = discrete_pinn.solve(key, space, N_EPOCHS, N_COLLOC) spaces.append(space_) errors_over_time.append(discrete_pinn.errors_over_time) print(f"\nSolving with the {method} method... Done\n") # %% fig, ax = plt.subplots(1, 2, figsize=(12, 5)) error_type = ["L2", "Linf"] for i in range(2): for j, (key, param) in enumerate(params.items()): ax[i].semilogy( jnp.linspace(DOM_T[0], DOM_T[1], nt + 1), errors_over_time[j][:, i], label=key, ) ax[i].set_xlabel("time") ax[i].set_ylabel(f"relative {error_type[i]} error") ax[i].set_title(f"Relative {error_type[i]} error vs time") ax[i].legend() ax[i].grid() plot_abstract_approx_spaces( spaces, DOM_X, solution=lambda x: exact_sol(jnp.ones_like(x) * DOM_T[-1], x), error=lambda x: exact_sol(jnp.ones_like(x) * DOM_T[-1], x), title=f"solution at final time t={DOM_T[-1]}", titles=[f"solution with {method} method" for method in params.keys()], ) plt.show() # # %% # %%