Source code for solver

# Copyright 2026 Philippe Billet assisted by LLMs in free mode: chatGPT, Qwen, Deepseek, Gemini, Claude, le chat Mistral.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
solver.py — Spectral PDE solver for 1D/2D equations with pseudo‑differential operators
============================================================================================

Overview
--------
The `solver` module provides a high‑performance spectral solver for partial differential equations in one and two spatial dimensions.  It is designed to handle a wide class of problems, including:

* Linear and nonlinear PDEs with periodic boundary conditions (native), plus heuristic 'nonperiodic'/'neumann' treatments for localized solutions on large domains (see "Boundary conditions" below).
* Time‑dependent evolution (first‑ or second‑order in time) and stationary problems.
* Equations involving pseudo‑differential operators (via `psiOp`), such as fractional Laplacians or non‑local terms.
* Source terms and arbitrary spatial derivatives.

The solver is built on **Fourier spectral methods** for spatial discretisation, ensuring exponential convergence for smooth solutions.  Time stepping is performed with either a simple exponential integrator, a fourth‑order **Exponential Time Differencing Runge–Kutta (ETD‑RK4)** scheme for first‑order equations, or explicit Runge–Kutta methods for second‑order equations and nonlinear problems.  For stationary pseudo‑differential equations, an **asymptotic inversion** of the operator is available.

Key features:

* Symbolic parsing of the PDE using SymPy – the user provides an equation in standard mathematical form.
* Automatic extraction of linear, nonlinear, source, and pseudo‑differential terms.
* Computation of the Fourier symbol of the linear operator (dispersion relation) from the equation.
* Dealiasing via sharp spectral cut‑off to control aliasing errors from nonlinear terms.
* Efficient FFT‑based application of linear and pseudo‑differential operators.
* Support for both 1D and 2D problems with uniform grids.
* Built‑in energy monitoring, CFL checks, and spectral symbol analysis.
* Rich visualisation: animated solutions, error plots, energy evolution, and 3D surface/2D image displays.
* Testing framework for comparison with exact solutions.
* Optional absorbing **sponge layer** at the domain edges, which damps outgoing waves and reduces the artificial re‑entry caused by periodic wrap‑around.

Mathematical background
-----------------------
**Spectral discretisation.**  The solution `u(x,t)` is approximated by its truncated Fourier series.  Spatial derivatives are replaced by multiplication with the corresponding wavenumber in Fourier space:

    ∂/∂x   →   i k , ∂²/∂x² →   -k² .

Nonlinear terms are evaluated in physical space and then transformed back (pseudo‑spectral approach).  Dealiasing is applied by zeroing out the highest one‑third of the Fourier modes (the 2/3‑rule).

**Linear operator.**  After parsing the PDE, the linear part is converted into a Fourier multiplier `L(k)` (or `L(kx,ky)`).  For a first‑order‑in‑time equation

    ∂ₜ u = L u + N(u) + f(x,t),

the variation‑of‑constants formula motivates exponential integrators.  The solver implements:

* **Exponential Euler** (first order): `uⁿ⁺¹ = e^{LΔt} uⁿ + Δt φ₁(LΔt) (N(uⁿ)+fⁿ)` with `φ₁(z) = (e^z-1)/z`.
* **ETD‑RK4** (fourth order, first‑order equations only): the Kassam–Trefethen Runge–Kutta scheme that uses exponentials of the linear part, achieving high accuracy and unconditional stability for the linear part of stiff problems.

For second‑order equations

∂ₜ² u + γ ∂ₜ u = L u + N(u) + f(x,t),

where γ ≥ 0 is a constant damping coefficient, the system is reduced to first order in time (∂ₜu = v, ∂ₜv = L u + N(u) + f − γ v). The solver provides:

* **Default exponential propagator**: an exact matrix exponential integrator for the damped linear part, valid for under‑, critically, and over‑damped modes (using the sinc function to handle the zero‑frequency limit safely).

* **Explicit RK4 (fourth order)**: a standard Runge‑Kutta scheme applied to the first‑order system (including the −γ v friction term).  This is subject to the CFL condition Δt ∝ Δx^(m/2) where m is the order of the linear operator L.  For stiff operators, this imposes severe time‑step restrictions.  (Note: despite historical naming, this is not an exponential integrator.)

* **Damped Leap‑frog (second order, for pseudo‑differential operators)**: an explicit finite‑difference scheme used when `psiOp` is present, where the friction term γ ∂ₜu is included implicitly in the update formula.

**Pseudo‑differential operators.**  When the equation contains `psiOp(p(x,ξ), u)`, the solver builds a `PseudoDifferentialOperator` object (from the companion `psiop` module) and applies it using Kohn–Nirenberg quantisation (fast Fourier for constant‑coefficient symbols, direct quadrature for spatially varying symbols).  For stationary problems, an asymptotic right inverse is constructed via symbolic series expansion.

**Stability.**  The solver checks the CFL condition based on the maximum group velocity derived from the dispersion relation.  It also verifies that the symbol satisfies the necessary conditions for well‑posedness (Re `L(k)` ≤ 0, sufficient high‑frequency dissipation, moderate growth).

**Sponge layer (absorbing boundary).**  Fourier spectral methods are intrinsically periodic: a wave leaving the domain through one edge re-enters through the opposite one.  To emulate an open (non‑reflecting) domain, the solver can add a damping term γ(x) ≥ 0 that is zero in the interior and grows smoothly to γ_max inside a layer near the edges of the (centred) domain [-Lx/2, Lx/2] (and [-Ly/2, Ly/2] in 2D):

    first order :   ∂ₜ u       = L u + N(u) + f − γ(x) u
    second order:   ∂ₜ² u + γ(x) ∂ₜ u = L u + N(u) + f

The profile is a polynomial ramp

    γ(x) = γ_max · ((|x| − x₀) / (Lx/2 − x₀))^p   for |x| > x₀,   γ(x) = 0 otherwise,

with x₀ = (Lx/2)(1 − w), where `w` is the relative width (`sponge_width`), γ_max the strength (`sponge_strength`) and p the order of the ramp (`sponge_order`).  In 2D, γ(x,y) = max(γ_x(x), γ_y(y)), so the corners receive the strongest damping.

The damping is treated by operator splitting: after each (spectral) time step the fields are multiplied by e^{−γ Δt}, except for the second‑order pseudo‑differential scheme, where the friction term γ∂ₜu is included implicitly in the leap‑frog update.  The sponge is a numerical device, not a physical boundary condition: it only attenuates the solution, it does not impose any value on it, and the physics inside the layer is modified.  Place all features of interest in the undamped interior.

**Boundary conditions.**  Only 'periodic' is exact: the FFT natively enforces u(x+L) = u(x), and no clipping is applied.  'nonperiodic' and 'neumann' are implemented by post-hoc clipping of the boundary nodes after each time step (u[0]=u[-1]=0 for Dirichlet, u[0]=u[1], u[-1]=u[-2] for Neumann, a first-order approximation).  They do NOT constitute a rigorous spectral boundary-value-problem enforcement.  They are accurate when the solution is localized and negligible (~machine precision) at the boundary, i.e. they emulate the whole-space Cauchy problem on a sufficiently large box.  If the solution reaches the boundary with non-negligible amplitude, the clipping creates a jump in the periodic extension (Gibbs phenomenon) that pollutes the whole domain.  A runtime guard (`boundary_tol`) warns when this happens.  For hard-wall reflections with constant, even symbols, use periodic BCs with the method of images (odd extension = Dirichlet, even extension = Neumann on a doubled domain).  For open domains, use periodic BCs with a sponge layer.  Note that for non-local operators these choices define different operators (the odd extension yields the *spectral* fractional Laplacian, not the *restricted* one).

References
----------
.. [1] Canuto, C., Hussaini, M. Y., Quarteroni, A., & Zang, T. A.  *Spectral Methods: Fundamentals in Single Domains*, Springer, 2006.
.. [2] Trefethen, L. N.  *Spectral Methods in MATLAB*, SIAM, 2000.
.. [3] Boyd, J. P.  *Chebyshev and Fourier Spectral Methods*, Dover, 2001.
.. [4] Hochbruck, M., & Ostermann, A.  "Exponential integrators", *Acta Numerica* 19, 209–286, 2010.
.. [5] Kassam, A.-K., & Trefethen, L. N.  "Fourth‑order time‑stepping for stiff PDEs", *SIAM J. Sci. Comput.* 26(4), 1214–1233, 2005.
"""

from imports import *
from psiop import *

_LEGACY_BC_CLIP = {'nonperiodic': 'zero', 'neumann': 'copy'}

def _normalize_bc(bc):
    """Return (canonical_bc, clip_mode). Legacy names are deprecated aliases."""
    if bc == 'periodic':
        return 'periodic', None
    if bc == 'nonperiodic':
        return 'nonperiodic', 'zero'
    if bc in _LEGACY_BC_CLIP:
        warnings.warn(
            f"boundary_condition='{bc}' is deprecated; use 'nonperiodic'. "
            "These modes were never a rigorous BVP enforcement (boundary-node "
            "clipping valid only for solutions that vanish at the boundary).",
            DeprecationWarning, stacklevel=3,
        )
        return 'nonperiodic', _LEGACY_BC_CLIP[bc]
    raise ValueError(
        f"Invalid boundary condition '{bc}'. "
        "Supported: 'periodic', 'nonperiodic' (deprecated aliases: "
        "'nonperiodic', 'neumann')."
    )

[docs] class PDESolver: """ A partial differential equation (PDE) solver based on **spectral methods** using Fourier transforms. This solver supports symbolic specification of PDEs via SymPy and numerical solution using high-order spectral techniques. It is designed for both **linear and nonlinear time-dependent PDEs**, as well as **stationary pseudo-differential problems**. Key Features: ------------- - Symbolic PDE parsing using SymPy expressions - 1D and 2D spatial domains with periodic boundary conditions - Fourier-based spectral discretization with dealiasing - Temporal integration schemes: - Default exponential time stepping - ETD-RK4 (Exponential Time Differencing Runge-Kutta of 4th order) - Nonlinear terms handled through pseudo-spectral evaluation - Built-in tools for: - Visualization of solutions and error surfaces - Symbol analysis of linear and pseudo-differential operators - Microlocal analysis (e.g., Hamiltonian flows) - CFL condition checking and numerical stability diagnostics - Optional sponge layer (absorbing region) at the domain edges to limit periodic wrap-around of outgoing waves (see `setup`) Supported Operators: -------------------- - Linear differential and pseudo-differential operators - Nonlinear terms up to second order in derivatives - Symbolic operator composition and adjoints - Asymptotic inversion of elliptic operators for stationary problems Example Usage: -------------- >>> import numpy as np >>> import sympy as sp >>> from IPython.display import HTML >>> from solver import PDESolver >>> >>> u = sp.Function('u') >>> t, x = sp.symbols('t x') >>> eq = sp.Eq(sp.diff(u(t, x), t), sp.diff(u(t, x), x, 2) + u(t, x)**2) >>> >>> def initial(x): ... return np.sin(x) >>> >>> solver = PDESolver(eq) >>> solver.setup(Lx=2*np.pi, Nx=128, Lt=1.0, Nt=1000, initial_condition=initial) >>> solver.solve() >>> ani = solver.animate() >>> HTML(ani.to_jshtml()) # Display animation in Jupyter notebook """ def __init__( self, equation: Eq, time_scheme: str = 'default', dealiasing_ratio: Optional[float] = None, compute_energy: bool = True ) -> None: """ Initialize the PDE solver with a given equation. This method analyzes the input partial differential equation (PDE), identifies the unknown function and its dependencies, determines whether the problem is stationary or time-dependent, and prepares symbolic and numerical structures for solving in spectral space. Supported features: - 1D and 2D problems - Time-dependent and stationary equations - Linear and nonlinear terms - Pseudo-differential operators via `psiOp` - Source terms and boundary conditions - Constant damping (γ ∂ₜu) for second-order equations The equation is parsed to extract linear, nonlinear, source, and pseudo-differential components. Symbolic manipulation is used to derive the Fourier representation of linear operators when applicable. Parameters ---------- equation : sympy.Eq The PDE expressed as a SymPy equation. time_scheme : str Temporal integration scheme: - 'default' for exponential - time-stepping or 'RK4' for fourth-order exponential - time differencing Runge–Kutta. dealiasing_ratio : float or None, optional (default None) Fraction of the Nyquist wavenumber retained by the sharp dealiasing cut-off. If None, it is chosen from the polynomial degree p of the nonlinear terms: 2/(p+1), i.e. 2/3 for quadratic terms and 1/2 for cubic ones (and 2/3 when the problem is linear or the nonlinearity is not polynomial). If a value is given that is too large for the detected degree, a warning is emitted. compute_energy : bool, optional (default True) Turn it off if setup is too long, there is maybe a problem during computation of the square root of the operator. Attributes initialized ---------------------- - self.u : the unknown function (e.g., u(t, x)) - self.dim : spatial dimension (1 or 2) - self.spatial_vars : list of spatial variables (e.g., [x] or [x, y]) - self.is_stationary : boolean indicating if the problem is stationary - self.linear_terms : dictionary mapping derivative orders to coefficients - self.nonlinear_terms : list of nonlinear expressions - self.source_terms : list of source functions - self.pseudo_terms : list of pseudo-differential operator expressions - self.has_psi : boolean indicating presence of pseudo-differential operators - self.fft / self.ifft : appropriate FFT routines based on spatial dimension - self.kx, self.ky : symbolic wavenumber variables for Fourier space - self.damping : float, constant damping coefficient γ for second-order equations Raises ------ ValueError If the equation does not contain exactly one unknown function, if unsupported dimensions are detected, or invalid dependencies. """ self.equation = equation self.time_scheme = time_scheme # 'default' or 'RK4' self.dealiasing_ratio = dealiasing_ratio self.compute_energy = compute_energy print("\n*********************************") print("* Partial differential equation *") print("*********************************\n") pprint(equation, num_columns=NUM_COLS) # Extract symbols and function from the equation functions = equation.atoms(Function) # Ignore the wrappers psiOp and Op excluded_wrappers = {'psiOp', 'Op'} # Extract the candidate fonctions (excluding wrappers) candidate_functions = [ f for f in functions if f.func.__name__ not in excluded_wrappers ] # Keep only user functions (u(x), u(x, t), etc.) candidate_functions = [ f for f in candidate_functions if isinstance(f, AppliedUndef) ] # Stationary detection: no dependence on t self.is_stationary = all( not any(str(arg) == 't' for arg in f.args) for f in candidate_functions ) if len(candidate_functions) != 1: print("candidate_functions :", candidate_functions) raise ValueError("The equation must contain exactly one unknown function") self.u = candidate_functions[0] self.u_eq = self.u args = self.u.args if self.is_stationary: if len(args) not in (1, 2): raise ValueError("Stationary problems must depend on 1 or 2 spatial variables") self.spatial_vars = args else: if len(args) < 2 or len(args) > 3: raise ValueError("The function must depend on t and at least one spatial variable (x [, y])") self.t = args[0] self.spatial_vars = args[1:] self.dim = len(self.spatial_vars) if self.dim == 1: self.x = self.spatial_vars[0] self.y = None elif self.dim == 2: self.x, self.y = self.spatial_vars else: raise ValueError("Only 1D and 2D problems are supported.") if self.dim == 1: self.fft = partial(fft, workers=FFT_WORKERS) self.ifft = partial(ifft, workers=FFT_WORKERS) else: # In 2D, try pyfftw for faster transforms (FFTW planning is done once at # first call thanks to pyfftw's interface cache). Fall back to scipy.fft # when pyfftw is not installed. try: import pyfftw import pyfftw.interfaces.numpy_fft as pyfftw_fft pyfftw.interfaces.cache.enable() # pyfftw's numpy interface uses 'threads' (not 'workers' like scipy.fft) self.fft = partial(pyfftw_fft.fft2, threads=FFT_WORKERS) self.ifft = partial(pyfftw_fft.ifft2, threads=FFT_WORKERS) print("ℹ️ 2D FFT backend: pyfftw (FFTW)") except ImportError: self.fft = partial(fft2, workers=FFT_WORKERS) self.ifft = partial(ifft2, workers=FFT_WORKERS) print("ℹ️ 2D FFT backend: scipy.fft (install pyfftw for better performance)") # Parse the equation self.linear_terms = {} self.nonlinear_terms = [] self.symbol_terms = [] self.source_terms = [] self.pseudo_terms = [] self.temporal_order = 0 # Order of the temporal derivative self.linear_terms, self.nonlinear_terms, self.symbol_terms, self.source_terms, self.pseudo_terms = self._parse_equation(equation) # flag : pseudo‑differential operator present ? self.has_psi = bool(self.pseudo_terms) if self.has_psi: self.is_spatial = False for coeff, expr in self.pseudo_terms: if expr.has(self.x) or (self.dim == 2 and expr.has(self.y)): self.is_spatial = True break if self.dim == 1: self.kx = symbols('kx') elif self.dim == 2: self.kx, self.ky = symbols('kx ky') self.damping = 0.0 # gamma in u_tt + gamma*u_t = ... (second-order equations only) if not self.is_stationary: time_derivs = [ deriv for deriv in self.linear_terms.keys() if isinstance(deriv, Derivative) and self.t in [var for var, _ in deriv.variable_count] ] if len(time_derivs) == 2: # Damped second-order equation: a*u_tt + b*u_t + ... = 0 t_order = lambda d: sum(n for var, n in d.variable_count if var == self.t) d2 = [d for d in time_derivs if t_order(d) == 2] d1 = [d for d in time_derivs if t_order(d) == 1] if len(d2) != 1 or len(d1) != 1: raise ValueError( "Supported temporal parts: a*du/dt, a*d2u/dt2 or a*d2u/dt2 + b*du/dt." ) gamma = simplify(self.linear_terms[d1[0]] / self.linear_terms[d2[0]]) if gamma.free_symbols: raise ValueError("The coefficient of du/dt must be constant " "(variable damping is not supported).") self.damping = float(gamma) # Keep a pure u_tt equation for the dispersion relation; the damping # enters the acceleration in _step_RK4_order2. del self.linear_terms[d1[0]] time_derivs = d2 elif len(time_derivs) > 2: raise ValueError( "The temporal part must be a*du/dt, a*d2u/dt2 or a*d2u/dt2 + b*du/dt." ) # The linear symbol L(k) (and the psi symbols) are already divided # by the coefficient `a` of the time derivative; N and f must be # too: a*du/dt = L'u + N' + f' <=> du/dt = L'u/a + N'/a + f'/a. if time_derivs: a_time = self.linear_terms[time_derivs[0]] if a_time != 1: self.nonlinear_terms = [n / a_time for n in self.nonlinear_terms] self.source_terms = [s_ / a_time for s_ in self.source_terms] # Dealiasing ratio: 2/(p+1) for a polynomial nonlinearity of degree p # (2/3 rule for quadratic terms, 1/2 rule for cubic terms, ...). self._nl_degree = self._nonlinear_degree() p_nl = self._nl_degree if dealiasing_ratio is None: if p_nl is not None and p_nl >= 3: self.dealiasing_ratio = 2.0 / (p_nl + 1) print(f"ℹ️ Polynomial nonlinearity of degree {p_nl}: " f"dealiasing_ratio set to 2/{p_nl + 1} = {self.dealiasing_ratio:.3f}") else: self.dealiasing_ratio = 2.0 / 3.0 if p_nl is None: print("ℹ️ Non-polynomial nonlinearity: dealiasing_ratio kept at 2/3 " "(aliasing cannot be excluded, check resolution).") else: self.dealiasing_ratio = dealiasing_ratio if (p_nl is not None and p_nl >= 3 and dealiasing_ratio > 2.0 / (p_nl + 1) + 1e-12): warnings.warn( f"Nonlinearity of degree {p_nl}: dealiasing_ratio=" f"{dealiasing_ratio:.3f} > 2/{p_nl + 1} = {2.0 / (p_nl + 1):.3f}; " "aliasing errors may pollute the retained modes.", RuntimeWarning, ) # Compute linear operator if not self.is_stationary: self._compute_linear_operator() else: self.psi_ops = [] for coeff, sym_expr in self.pseudo_terms: psi = PseudoDifferentialOperator(sym_expr, self.spatial_vars, self.u, mode='symbol') self.psi_ops.append((coeff, psi)) # --- Inside __init__ --- self.energy_history = [] self.accumulated_work = 0.0 self.work_history = [] self.mechanical_energy_history = [] def _parse_equation( self, equation: Union[Eq, Expr] ) -> Tuple[Dict[Any, Expr], List[Expr], List[Tuple[Any, Expr]], List[Expr], List[Tuple[Any, Expr]]]: """ Parse the PDE to separate linear and nonlinear terms, symbolic operators (Op), source terms, and pseudo-differential operators (psiOp). This method rewrites the input equation in standard form (lhs - rhs = 0), expands it, and classifies each term into one of the following categories: - Linear terms involving derivatives or the unknown function u - Nonlinear terms (products with u, powers of u, etc.) - Symbolic pseudo-differential operators (Op) - Source terms (independent of u) - Pseudo-differential operators (psiOp) Parameters ---------- equation : sympy.Eq The partial differential equation to be analyzed. Can be provided as an Eq object or a sympy expression. Returns ------- tuple A 5-tuple containing: - linear_terms (dict): Mapping from derivative/function to coefficient. - nonlinear_terms (list): List of terms classified as nonlinear. - symbol_terms (list): List of (coefficient, symbolic operator) pairs. - source_terms (list): List of terms independent of the unknown function. - pseudo_terms (list): List of (coefficient, pseudo-differential symbol) pairs. Notes ----- - If `psiOp` is present in the equation, expansion is skipped for safety. - When `psiOp` is used, only nonlinear terms, source terms, and possibly a time derivative are allowed; other linear terms and symbolic operators (Op) are forbidden. - Classification logic includes: - Detection of nonlinear structures like products or powers of u - Mixed terms involving both u and its derivatives - External symbolic operators (Op) and pseudo-differential operators (psiOp) - For second-order equations, detects the form a*∂ₜ²u + b*∂ₜu, extracts the constant damping γ = b/a, and removes the first derivative from the linear terms to isolate the pure dispersion relation. """ def _is_nonlinear_term(term: Expr, u_func: Function) -> bool: """ Determine whether a SymPy expression constitutes a nonlinear term with respect to the dependent variable u_func (e.g. u(t, x)). A term is considered nonlinear if any of the following hold: 1. A nonlinear function (Abs, sin, exp, ...) is applied to any expression containing u or its derivatives. 2. Any Pow node whose base contains u or a Derivative of u, with exponent != 1 (including negative exponents, i.e. rational terms). 3. A product (Mul) contains two or more factors that each involve u or any Derivative of u — covers u*u_x, u_x*u_xx, u_x*u_y, etc. 4. A single Derivative of u appears inside a nonlinear function, e.g. Abs(u_x), sin(u_xx). Parameters ---------- term : sympy.Expr The expression to classify. u_func : sympy.Function The dependent variable, e.g. u(t, x). Returns ------- bool True if the term is nonlinear in u_func, False otherwise. """ def _contains_u(expr: Expr) -> bool: """True if expr involves u or any Derivative of u.""" return expr.has(u_func) def _is_derivative_of_u(expr: Expr) -> bool: """True if expr is a Derivative whose function is u.""" return (isinstance(expr, Derivative) and expr.args[0].func == u_func.func) def _is_u_or_derivative(expr: Expr) -> bool: """True if expr is u itself or a Derivative of u.""" return expr == u_func or _is_derivative_of_u(expr) # 1. Nonlinear function applied to anything containing u or its derivatives # e.g. Abs(u), sin(u), exp(u_x), Abs(u_xx) for sub in preorder_traversal(term): if (isinstance(sub, Function) and sub.func != u_func.func # exclude u(t,x) itself and not isinstance(sub, Derivative) # exclude Derivative nodes and _contains_u(sub)): return True # 2. Pow whose base contains u or a Derivative of u, with exponent != 1 # e.g. u**2, u**-1, u_x**2, (1 + u)**-1, (u_xx)**3 for pow_term in term.atoms(Pow): if _contains_u(pow_term.base) and pow_term.exp != 1: return True # 3. Product containing two or more factors that each involve u or D(u) # e.g. u*u_x, u_x*u_xx, u_x*u_y, u*u_xxx if isinstance(term, Mul): u_bearing_factors = [ f for f in term.args if _contains_u(f) ] if len(u_bearing_factors) >= 2: return True # 4. Add: recurse into each summand — catches mixed sums like u_x**2 + u*u_xx if isinstance(term, Add): if any(_is_nonlinear_term(arg, u_func) for arg in term.args): return True return False print("\n********************") print("* Equation parsing *") print("********************\n") if isinstance(equation, Eq): lhs = equation.lhs - equation.rhs else: lhs = equation print(f"\nEquation rewritten in standard form: {lhs}") if lhs.has(psiOp): print("⚠️ psiOp detected: skipping expansion for safety") lhs_expanded = lhs else: lhs_expanded = expand(lhs) print(f"\nExpanded equation: {lhs_expanded}") linear_terms = {} nonlinear_terms = [] symbol_terms = [] source_terms = [] pseudo_terms = [] for term in lhs_expanded.as_ordered_terms(): print(f"Analyzing term: {term}") if isinstance(term, psiOp): expr = term.args[0] pseudo_terms.append((1, expr)) print(" --> Classified as pseudo linear term (psiOp)") continue # Otherwise, look for psiOp inside (general case) if term.has(psiOp): psiops = term.atoms(psiOp) for psi in psiops: try: coeff = simplify(term / psi) expr = psi.args[0] pseudo_terms.append((coeff, expr)) print(" --> Classified as pseudo linear term (psiOp)") except Exception as e: print(f" ⚠️ Failed to extract psiOp coefficient in term: {term}") print(f" Reason: {e}") nonlinear_terms.append(term) print(" --> Fallback: classified as nonlinear") continue if term.has(Op): ops = term.atoms(Op) for op in ops: coeff = term / op expr = op.args[0] symbol_terms.append((coeff, expr)) print(" --> Classified as symbolic linear term (Op)") continue if _is_nonlinear_term(term, self.u): nonlinear_terms.append(-term) print(" --> Classified as nonlinear") continue derivs = term.atoms(Derivative) if derivs: deriv = derivs.pop() coeff = term / deriv print(f" Derivative found: {deriv}") if coeff.free_symbols & (set(self.spatial_vars) | {self.t}): if any(var == self.t for var, _ in deriv.variable_count): raise ValueError(f"A variable coefficient in front of a time derivative is not supported: {term}") nonlinear_terms.append(-term) print(" --> Classified as variable-coefficient (pointwise) term") else: linear_terms[deriv] = linear_terms.get(deriv, 0) + coeff print(" --> Classified as linear") elif self.u in term.atoms(Function): coeff = simplify(term / self.u) if coeff.free_symbols & (set(self.spatial_vars) | {self.t}): # variable coefficient: evaluate pointwise, like a nonlinear term nonlinear_terms.append(-term) print(" --> Classified as variable-coefficient (pointwise) term") else: linear_terms[self.u] = linear_terms.get(self.u, 0) + coeff print(" --> Classified as linear") else: source_terms.append(-term) print(" --> Classified as source term") if pseudo_terms: # Check if a time derivative is present among the linear terms has_time_derivative = any( isinstance(term, Derivative) and self.t in [v for v, _ in term.variable_count] for term in linear_terms ) # Extract non-temporal linear terms (pure spatial derivatives of u, # or terms that mix spatial derivatives without t) other_linear_terms = { term: coeff for term, coeff in linear_terms.items() if not ( isinstance(term, Derivative) and self.t in [v for v, _ in term.variable_count] ) and term != self.u # exclusion of the simple u term (without derivative) } if other_linear_terms: # Instead of forbidding these, fold them into a pseudo-differential # operator acting on u, so they end up handled by the same psiOp # machinery as the rest of the equation. var_u = self.u.func(self.spatial_vars) # u(x) or u(x, y), stripped of t def _to_var_u(term): """Rewrite a pure-spatial Derivative of self.u in terms of var_u.""" if term == self.u: return var_u if isinstance(term, Derivative): diff_args = [v for v, c in term.variable_count for _ in range(c)] return Derivative(var_u, *diff_args) return term expr = sum(coeff * _to_var_u(term) for term, coeff in other_linear_terms.items()) print(f" Converting invalid linear terms into a pseudo-differential operator: {expr}") op = PseudoDifferentialOperator( expr=expr, vars_x=self.spatial_vars, var_u=var_u, mode='auto', ) # NOTE: assumes PseudoDifferentialOperator exposes the resulting # symbol as `op.symbol` — adjust to whatever attribute/method # your class actually uses (e.g. op.get_symbol()). pseudo_terms.append((1, op.symbol)) # Drop the now-converted terms so they aren't double-counted for term in other_linear_terms: del linear_terms[term] if symbol_terms: raise ValueError( "When psiOp is used, symbolic operators (Op) are forbidden. " "Only nonlinear terms, source terms, a time derivative, and " "spatial linear terms (now converted to psiOp) are allowed." ) print(f"Final linear terms: {linear_terms}") print(f"Final nonlinear terms: {nonlinear_terms}") print(f"Symbol terms: {symbol_terms}") print(f"Pseudo terms: {pseudo_terms}") print(f"Source terms: {source_terms}") return linear_terms, nonlinear_terms, symbol_terms, source_terms, pseudo_terms def _compute_linear_operator(self) -> None: """ Compute the symbolic Fourier representation L(k) of the linear operator derived from the linear part of the PDE. This method constructs a dispersion relation by applying each symbolic derivative to a plane wave exp(i(k·x - ωt)) and extracting the resulting expression. It handles arbitrary derivative combinations and includes symbolic and pseudo-differential terms. Steps: ------- 1. Construct a plane wave φ(x, t) = exp(i(k·x - ωt)). 2. Apply each term from self.linear_terms to φ. 3. Normalize by φ and simplify to obtain L(k). 4. Include symbolic terms (e.g., psiOp) if present. 5. Detect the temporal order from the dispersion relation. 6. Build the numerical function L(k) via lambdify. Sets: ----- - self.L_symbolic : sympy.Expr Symbolic form of L(k). - self.L : callable Numerical function of L(kx[, ky]). - self.omega : callable or None Frequency root ω(k), if available. - self.temporal_order : int Order of time derivatives detected. - self.psi_ops : list of (coeff, PseudoDifferentialOperator) Pseudo-differential terms present in the equation. Raises: ------- ValueError if the dimension is unsupported or the dispersion relation fails. """ print("\n*******************************") print("* Linear operator computation *") print("*******************************\n") # --- Step 1: symbolic variables --- omega = symbols("omega") if self.dim == 1: kvars = [symbols("kx")] space_vars = [self.x] elif self.dim == 2: kvars = symbols("kx ky") space_vars = [self.x, self.y] else: raise ValueError("Only 1D and 2D are supported.") kdict = dict(zip(space_vars, kvars)) self.k_symbols = kvars # Plane wave expression phase = sum(k * x for k, x in zip(kvars, space_vars)) - omega * self.t plane_wave = exp(I * phase) # --- Step 2: build lhs expression from linear terms --- lhs = 0 for deriv, coeff in self.linear_terms.items(): if isinstance(deriv, Derivative): total_factor = 1 for var, n in deriv.variable_count: if var == self.t: total_factor *= (-I * omega)**n elif var in kdict: total_factor *= (I * kdict[var])**n else: raise ValueError(f"Unknown variable {var} in derivative") lhs += coeff * total_factor * plane_wave elif deriv == self.u: lhs += coeff * plane_wave else: raise ValueError(f"Unsupported linear term: {deriv}") # --- Step 3: dispersion relation --- equation = simplify(lhs / plane_wave) print("\nCharacteristic equation before symbol treatment:") pprint(equation, num_columns=NUM_COLS) print("\n--- Symbolic symbol analysis ---") symb_omega = 0 symb_k = 0 for coeff, symbol in self.symbol_terms: if symbol.has(omega): # Ajouter directement les termes dépendant de omega symb_omega += coeff * symbol elif any(symbol.has(k) for k in self.k_symbols): symb_k += coeff * symbol.subs(dict(zip(symbol.free_symbols, self.k_symbols))) print(f"symb_omega: {symb_omega}") print(f"symb_k: {symb_k}") equation = equation + symb_omega + symb_k print("\nRaw characteristic equation:") pprint(equation, num_columns=NUM_COLS) # Temporal derivative order detection try: poly_eq = Eq(equation, 0) poly = poly_eq.lhs.as_poly(omega) self.temporal_order = poly.degree() if poly else 0 except Exception as e: warnings.warn(f"Could not determine temporal order: {e}", RuntimeWarning) self.temporal_order = 0 print(f"Temporal order from dispersion relation: {self.temporal_order}") if self.pseudo_terms: coeff_time = 1 for term, coeff in self.linear_terms.items(): if isinstance(term, Derivative) and any(var == self.t for var, _ in term.variable_count): coeff_time = coeff print(f"✅ Time derivative coefficient detected: {coeff_time}") self.psi_ops = [] for coeff, sym_expr in self.pseudo_terms: psi = PseudoDifferentialOperator( sym_expr / coeff_time, self.spatial_vars, self.u, mode='symbol', apply_backend="peetre", # <--- Dispatch apply() to apply_peetre() compute_peetre=True, # <--- Precompute decomposition once ) self.psi_ops.append((coeff, psi)) # For second-order-in-time equations, precompute the operator # Op(P^{1/2}) where P is the total pseudo-differential symbol. if self.temporal_order == 2: # 1. Build the total operator first total_symbol = sum(coeff * psi.expr for coeff, psi in self.psi_ops) total_op = PseudoDifferentialOperator( total_symbol, self.spatial_vars, self.u, mode='symbol', apply_backend="direct", # <--- Also optimize energy monitoring compute_peetre=False, ) if self.compute_energy: # 2. Compute the fractional power P^{1/2} # We use order=1 to capture the first microlocal spatial corrections. # (If you only want the principal symbol, use order=0). # Note: We drop Abs() to preserve the C^\infty smoothness required # for pseudo-differential calculus. If the operator is positive-definite, # this is exact. If not, it correctly handles complex branch cuts. energy_symbol = total_op.fractional_power( alpha=0.5, order=1, method='symbolic' ) # 3. Create the final energy operator self._energy_psi_op = PseudoDifferentialOperator( energy_symbol, self.spatial_vars, self.u, mode='symbol', apply_backend="direct", # <--- Also optimize energy monitoring compute_peetre=False, ) # 4. Check for spatial dependence self._energy_is_spatial = any( energy_symbol.has(var) for var in self.spatial_vars ) else: dispersion = solve(Eq(equation, 0), omega) if not dispersion: raise ValueError("No solution found for omega") print("\n--- Solutions found ---") pprint(dispersion, num_columns=NUM_COLS) if self.temporal_order == 2: omega_expr = simplify(sqrt(dispersion[0]**2)) self.omega_symbolic = omega_expr self.omega = lambdify(self.k_symbols, omega_expr, "numpy") self.L_symbolic = -omega_expr**2 else: self.L_symbolic = -I * dispersion[0] self.L = lambdify(self.k_symbols, self.L_symbolic, "numpy") print("\n--- Final linear operator ---") pprint(self.L_symbolic, num_columns=NUM_COLS) def _linear_rhs(self, u: np.ndarray, is_v: bool = False) -> np.ndarray: """ Apply the linear operator (in Fourier space) to the field u or v. Parameters ---------- u : np.ndarray Input solution array. is_v : bool Whether to apply the operator to v instead of u. Returns ------- np.ndarray Result of applying the linear operator. """ if self.dim == 1: self.symbol_u = np.array(self.L(self.KX), dtype=np.complex128) self.symbol_v = self.symbol_u # même opérateur pour u et v elif self.dim == 2: self.symbol_u = np.array(self.L(self.KX, self.KY), dtype=np.complex128) self.symbol_v = self.symbol_u u_hat = self.fft(u) u_hat *= self.symbol_v if is_v else self.symbol_u u_hat *= self.dealiasing_mask return self.ifft(u_hat)
[docs] def setup( self, Lx: float, Ly: Optional[float] = None, Nx: Optional[int] = None, Ny: Optional[int] = None, Lt: float = 1.0, Nt: int = 100, boundary_condition: str = 'periodic', boundary_tol: float = 1e-8, periodic_edge_tol=None, initial_condition: Optional[Callable[..., np.ndarray]] = None, initial_velocity: Optional[Callable[..., np.ndarray]] = None, n_frames: int = 100, plot: bool = True, sponge: bool = False, sponge_width: float = 0.15, sponge_strength: float = 10.0, sponge_order: int = 4, ) -> None: """ Configure the spatial/temporal grid and initialize the solution field. This method sets up the computational domain, initializes spatial and temporal grids, applies boundary conditions, and prepares symbolic and numerical operators. It also performs essential analyses such as: - CFL condition verification (for stability) - Symbol analysis (e.g., dispersion relation, regularity) - Wave propagation analysis for second-order equations If pseudo-differential operators (ψOp) are present, symbolic analysis is skipped in favor of interactive exploration via `interactive_symbol_analysis`. Parameters ---------- Lx : float Size of the spatial domain along x-axis. Ly : float, optional Size of the spatial domain along y-axis (for 2D problems). Nx : int Number of spatial points along x-axis. Ny : int, optional Number of spatial points along y-axis (for 2D problems). Lt : float, default=1.0 Total simulation time. Nt : int, default=100 Number of time steps. initial_condition : callable Function returning the initial state u(x, 0) or u(x, y, 0). initial_velocity : callable, optional Function returning the initial time derivative ∂ₜu(x, 0) or ∂ₜu(x, y, 0), required for second-order equations. n_frames : int, default=100 Number of time frames to store during simulation for visualization or output. boundary_condition : str, default='periodic' 'periodic' (exact, native FFT) or 'nonperiodic' (heuristic: direct quadrature backend + clipping of boundary nodes to 0 after each step; valid only for solutions negligible at the boundary, see `boundary_tol`). 'nonperiodic'/'neumann' are deprecated aliases. 'nonperiodic' requires equations defined through `psiOp`. boundary_tol : float, default=1e-8 Relative threshold on the correction applied by the clipping (max |Δu| / max |u|). If exceeded, a RuntimeWarning is emitted once; the largest correction seen is stored in `self._bc_max_correction`. Ignored for 'periodic'. periodic_edge_tol : float or None, default=None Only for 'periodic'. If set, the amplitude of the solution on the edge nodes (relative to max|u|) is monitored and a RuntimeWarning is emitted once if it exceeds this value, meaning the solution wraps around the torus (use when periodic BCs emulate a large box, i.e. a localized solution). Nothing is clipped. None disables the check (legitimately periodic problems). plot : bool, default=True If True, diagnostic plots are displayed during setup (symbol analysis and, when the sponge is active, the damping profile). sponge : bool, default=False Activate an absorbing sponge layer near the edges of the domain. Because the Fourier discretisation is periodic, waves leaving the domain on one side re-enter on the opposite side; the sponge damps them before they wrap around. The damping profile γ(x) (γ(x, y) in 2D) is zero in the interior and increases smoothly to `sponge_strength` at the boundary. It is applied at every time step in `solve()`. The domain is assumed to be centred at the origin, i.e. [-Lx/2, Lx/2] (and [-Ly/2, Ly/2]). sponge_width : float, default=0.15 Width of the sponge on each side, as a fraction of the half-domain length (not of the full length). For example, 0.15 means that the outer 15 % of [0, Lx/2] on each side is damped, i.e. a physical thickness of 0.15·Lx/2 per edge. Must lie in (0, 1]. Wider layers absorb more gently and reflect less, but reduce the usable interior. Ignored if `sponge=False`. sponge_strength : float, default=10.0 Maximum damping rate γ_max (in units of 1/time) reached at the edge of the domain. It should be large enough to absorb the wave during its crossing of the layer (rough guide: the amplitude attenuation of a wave with speed c crossing the layer once is exp(−γ_max · d / ((p+1)·c)), where d is the layer thickness and p = `sponge_order`), but not so large that the profile becomes abrupt, which causes spurious reflections and, for explicit schemes, stiffness. Ignored if `sponge=False`. sponge_order : int, default=4 Exponent p of the polynomial ramp γ ∝ (distance into the layer)^p. Higher orders give a smoother onset (fewer reflections at the interface between interior and sponge) but concentrate the damping near the edge. Values 2–4 are typical. Ignored if `sponge=False`. Raises ------ ValueError If mandatory parameters are missing (e.g., Nx not given in 1D, Ly/Ny not given in 2D). Notes ----- - The spatial discretization assumes periodic boundary conditions by default. - Fourier transforms are computed using real-to-complex FFTs (`scipy.fft.fft`, `fft2`). - Frequency arrays (`KX`, `KY`) are defined following standard spectral conventions. - Dealiasing is applied using a sharp cutoff filter at a fraction of the maximum frequency. - For second-order equations, initial acceleration is derived from the governing operator. - Symbolic analysis includes plotting of the symbol's real/imaginary/absolute values and dispersion relation. - The sponge profile is stored in `self.sponge_profile` (ndarray of shape (Nx,) in 1D or (Nx, Ny) in 2D, `None` if disabled). - How the damping is applied depends on the time stepper: * first-order equations and the default / ETD-RK4 second-order schemes: after each step, u (and the velocity v for second-order equations) is multiplied by exp(−γ Δt); * second-order equations with `psiOp`: the friction term γ ∂ₜu is included in the leap-frog update, which is then divided by (1 + γ Δt). The two forms are equivalent to first order in Δt, but they do not damp the amplitude at exactly the same rate (for a wave, the multiplicative form gives e^{−γt}, the friction form e^{−γt/2}). - The sponge is not a boundary condition. It reduces wrap-around artefacts but does not remove them entirely; check the sensitivity of the results to `sponge_width` and `sponge_strength`. - The sponge acts on the solution itself, so it is not compatible with conservation checks: the energy diagnostics are no longer conserved when the sponge is active. - With `plot=True`, the damping profile is displayed so that its extent can be verified. See Also -------- setup_1D : Sets up internal variables for one-dimensional problems. setup_2D : Sets up internal variables for two-dimensional problems. initialize_conditions : Applies initial data and enforces compatibility. check_cfl_condition : Verifies time step against stability constraints. plot_symbol : Visualizes the linear operator’s symbol in frequency space. analyze_wave_propagation : Analyzes group velocity. interactive_symbol_analysis : Interactive tools for ψOp-based equations. _build_sponge_1d : Builds the 1D sponge damping profile γ(x). _build_sponge_2d : Builds the 2D sponge damping profile γ(x, y). _plot_sponge_profile : Displays the sponge profile for verification. """ # Temporal parameters self.Lt, self.Nt = Lt, Nt self.dt = Lt / Nt self.n_frames = n_frames self.frames = [] self.initial_condition = initial_condition self.boundary_condition, self._bc_clip = _normalize_bc(boundary_condition) self.boundary_tol = boundary_tol self._bc_max_correction = 0.0 self._bc_warned = False self.periodic_edge_tol = periodic_edge_tol self._edge_max = 0.0 self._edge_warned = False self.plot = plot if self.boundary_condition == 'nonperiodic' and not self.has_psi: raise ValueError( "Nonperiodic boundary conditions require the equation to be defined via a pseudo-differential operator (psiOp). " "Please provide an equation involving psiOp for non-periodic boundary treatment." ) # Dimension checks if self.dim == 1: if Nx is None: raise ValueError("Nx must be specified in 1D.") self._setup_1D(Lx, Nx) else: if None in (Ly, Ny): raise ValueError("In 2D, Ly and Ny must be provided.") self._setup_2D(Lx, Ly, Nx, Ny) # Pre-compile the nonlinear terms once (avoids lambdify at every call) self._compiled_nl = None self._t_current = 0.0 if not self.is_stationary: self._precompile_nonlinear_funcs() # Initialization of solution and velocities if not self.is_stationary: self._initialize_conditions(initial_condition, initial_velocity) # Pre-compile lambdified source functions once (avoids re-creating them at every time step) self._precompile_source_funcs() self.sponge_profile = None if sponge: self.sponge_width = sponge_width self.sponge_strength = sponge_strength self.sponge_order = sponge_order if self.dim == 1: self.sponge_profile = self._build_sponge_1d( sponge_width, sponge_strength, sponge_order ) elif self.dim == 2: self.sponge_profile = self._build_sponge_2d( sponge_width, sponge_strength, sponge_order ) if self.plot: self._plot_sponge_profile() # Symbol analysis if present if self.has_psi: print("⚠️ For psiOp, use interactive_symbol_analysis.") else: if self.L_symbolic == 0: raise ValueError("Linear operator is null: add a small Laplacian regularization (e.g. nu*u_xx).") else: self._check_cfl_condition() self._check_symbol_conditions() if plot: self._plot_symbol() if self.temporal_order == 2: self._analyze_wave_propagation()
def _setup_1D(self, Lx: float, Nx: int) -> None: """ Configure internal variables for one-dimensional (1D) problems. This private method initializes spatial and frequency grids, applies dealiasing, and prepares either pseudo-differential symbols or linear operators for use in time evolution. It assumes periodic boundary conditions and uses real-to-complex FFT conventions. The spatial domain is centered at zero: [-Lx/2, Lx/2]. Parameters ---------- Lx : float Physical size of the spatial domain along the x-axis. Nx : int Number of grid points in the x-direction. Attributes Set -------------- - self.Lx : float Size of the spatial domain. - self.Nx : int Number of spatial points. - self.x_grid : np.ndarray 1D array of spatial coordinates. - self.X : np.ndarray Alias to `self.x_grid`, used in physical space computations. - self.kx : np.ndarray Array of wavenumbers corresponding to the Fourier transform. - self.KX : np.ndarray Alias to `self.kx`, used in frequency space computations. - self.dealiasing_mask : np.ndarray Boolean mask used to suppress aliased frequencies during nonlinear calculations. - self.exp_L : np.ndarray Exponential of the linear operator scaled by time step: exp(L(k) · dt). - self.omega_val : np.ndarray Frequency values ω(k) = Re[√(L(k))] used in second-order time stepping. - self.cos_omega_dt, self.sin_omega_dt : np.ndarray Cosine and sine of ω(k)·dt for dispersive propagation. - self.inv_omega : np.ndarray Inverse of ω(k), used to avoid division-by-zero in time stepping. Notes ----- - Frequencies are computed using `scipy.fft.fftfreq` and then shifted to center zero frequency. - Dealiasing is applied using a sharp cutoff filter based on `self.dealiasing_ratio`. - If pseudo-differential operators (ψOp) are present, symbolic tables are precomputed via `prepare_symbol_tables`. - For second-order equations, the dispersion relation ω(k) is extracted from the linear operator L(k). See Also -------- setup_2D : Equivalent setup for two-dimensional problems. prepare_symbol_tables : Precomputes symbolic arrays for ψOp evaluation. setup_omega_terms : Sets up terms involving ω(k) for second-order evolution. """ self.Lx, self.Nx = Lx, Nx self.x_grid = np.linspace(-Lx/2, Lx/2, Nx, endpoint=False) self.X = self.x_grid self.kx = 2 * np.pi * fftfreq(Nx, d=Lx / Nx) self.KX = self.kx # Dealiasing mask k_max = self.dealiasing_ratio * np.max(np.abs(self.kx)) self.dealiasing_mask = (np.abs(self.KX) <= k_max) # Preparation of symbol or linear operator if self.has_psi: self._prepare_symbol_tables() else: L_vals = np.array(self.L(self.KX), dtype=np.complex128) self.exp_L = np.exp(L_vals * self.dt) self.phi1_L = self._phi1(L_vals * self.dt) if self.temporal_order == 2: omega_val = self.omega(self.KX) self._setup_omega_terms(omega_val) def _setup_2D(self, Lx: float, Ly: float, Nx: int, Ny: int) -> None: """ Configure internal variables for two-dimensional (2D) problems. This private method initializes spatial and frequency grids, applies dealiasing, and prepares either pseudo-differential symbols or linear operators for use in time evolution. It assumes periodic boundary conditions and uses real-to-complex FFT conventions. The spatial domain is centered at zero: [-Lx/2, Lx/2] × [-Ly/2, Ly/2]. Parameters ---------- Lx : float Physical size of the spatial domain along the x-axis. Ly : float Physical size of the spatial domain along the y-axis. Nx : int Number of grid points along the x-direction. Ny : int Number of grid points along the y-direction. Attributes Set -------------- - self.Lx, self.Ly : float Size of the spatial domain in each direction. - self.Nx, self.Ny : int Number of spatial points in each direction. - self.x_grid, self.y_grid : np.ndarray 1D arrays of spatial coordinates in x and y directions. - self.X, self.Y : np.ndarray 2D meshgrids of spatial coordinates for physical space computations. - self.kx, self.ky : np.ndarray Arrays of wavenumbers corresponding to Fourier transforms in x and y directions. - self.KX, self.KY : np.ndarray Meshgrids of wavenumbers used in frequency space computations. - self.dealiasing_mask : np.ndarray Boolean mask used to suppress aliased frequencies during nonlinear calculations. - self.exp_L : np.ndarray Exponential of the linear operator scaled by time step: exp(L(kx, ky) · dt). - self.omega_val : np.ndarray Frequency values ω(kx, ky) = Re[√(L(kx, ky))] used in second-order time stepping. - self.cos_omega_dt, self.sin_omega_dt : np.ndarray Cosine and sine of ω(kx, ky)·dt for dispersive propagation. - self.inv_omega : np.ndarray Inverse of ω(kx, ky), used to avoid division-by-zero in time stepping. Notes ----- - Frequencies are computed using `scipy.fft.fftfreq` and then shifted to center zero frequency. - Dealiasing is applied using a sharp cutoff filter based on `self.dealiasing_ratio`. - If pseudo-differential operators (ψOp) are present, symbolic tables are precomputed via `prepare_symbol_tables`. - For second-order equations, the dispersion relation ω(kx, ky) is extracted from the linear operator L(kx, ky). See Also -------- setup_1D : Equivalent setup for one-dimensional problems. prepare_symbol_tables : Precomputes symbolic arrays for ψOp evaluation. setup_omega_terms : Sets up terms involving ω(kx, ky) for second-order evolution. """ self.Lx, self.Ly = Lx, Ly self.Nx, self.Ny = Nx, Ny self.x_grid = np.linspace(-Lx/2, Lx/2, Nx, endpoint=False) self.y_grid = np.linspace(-Ly/2, Ly/2, Ny, endpoint=False) self.X, self.Y = np.meshgrid(self.x_grid, self.y_grid, indexing='ij') self.kx = 2 * np.pi * fftfreq(Nx, d=Lx / Nx) self.ky = 2 * np.pi * fftfreq(Ny, d=Ly / Ny) self.KX, self.KY = np.meshgrid(self.kx, self.ky, indexing='ij') # Dealiasing mask kx_max = self.dealiasing_ratio * np.max(np.abs(self.kx)) ky_max = self.dealiasing_ratio * np.max(np.abs(self.ky)) self.dealiasing_mask = (np.abs(self.KX) <= kx_max) & (np.abs(self.KY) <= ky_max) # Preparation of symbol or linear operator if self.has_psi: self._prepare_symbol_tables() else: L_vals = self.L(self.KX, self.KY) self.exp_L = np.exp(L_vals * self.dt) self.phi1_L = self._phi1(L_vals * self.dt) if self.temporal_order == 2: omega_val = self.omega(self.KX, self.KY) self._setup_omega_terms(omega_val) def _build_sponge_1d( self, width: float = 0.15, strength: float = 10.0, order: int = 4, ) -> np.ndarray: """ Build a 1D sponge damping profile γ(x). The profile vanishes in the interior |x| ≤ x₀ and grows polynomially up to `strength` at the domain edges: γ(x) = strength · ((|x| − x₀) / (L/2 − x₀))^order for |x| > x₀, with x₀ = (L/2)(1 − width). The domain is assumed centred at 0. Parameters ---------- width : float Fraction of the half-domain used for the sponge on each side. E.g. width=0.15 means 15 % of [0, L/2] on each side. strength : float Maximum damping rate γ_max (1/time) at the boundary. order : int Polynomial order of the ramp (2–4 typical). Higher values give a smoother transition and fewer reflections. Returns ------- ndarray of shape (Nx,) The damping profile γ(x) ≥ 0. """ x = self.x_grid L_half = self.Lx / 2.0 x0 = L_half * (1.0 - width) gamma = np.zeros(self.Nx) mask = np.abs(x) > x0 gamma[mask] = strength * ((np.abs(x[mask]) - x0) / (L_half - x0)) ** order return gamma def _build_sponge_2d( self, width: float = 0.15, strength: float = 10.0, order: int = 4, ) -> np.ndarray: """ Build a 2D sponge damping profile γ(x, y). Separable 1D profiles γ_x(x) and γ_y(y) are built with the same formula as in `_build_sponge_1d` (using Lx and Ly respectively), and combined as γ(x, y) = max(γ_x(x), γ_y(y)). The maximum (rather than the sum) keeps γ ≤ strength everywhere, while the corners are damped as strongly as the edges. The same `width` fraction is used along both axes. Parameters ---------- width, strength, order : See `_build_sponge_1d`. Returns ------- ndarray of shape (Nx, Ny) The damping profile γ(x, y) ≥ 0. """ x, y = self.x_grid, self.y_grid Lx_half, Ly_half = self.Lx / 2.0, self.Ly / 2.0 x0 = Lx_half * (1.0 - width) y0 = Ly_half * (1.0 - width) gamma_x = np.zeros(self.Nx) mask_x = np.abs(x) > x0 gamma_x[mask_x] = strength * ((np.abs(x[mask_x]) - x0) / (Lx_half - x0)) ** order gamma_y = np.zeros(self.Ny) mask_y = np.abs(y) > y0 gamma_y[mask_y] = strength * ((np.abs(y[mask_y]) - y0) / (Ly_half - y0)) ** order # Take the max so corners get full damping from both axes return np.maximum(gamma_x[:, None], gamma_y[None, :]) def _setup_omega_terms(self, omega_val: np.ndarray) -> None: """ Initialize terms derived from the angular frequency ω for time evolution. This private method precomputes and stores key trigonometric and inverse quantities based on the dispersion relation ω(k), used in second-order time integration schemes. These values are essential for solving wave-like equations with dispersive behavior: cos(ω·dt), sin(ω·dt)/ω The inverse frequency terms are computed safely to avoid division by zero at ω=0. Additionally, it computes the exact damped propagator matrix for constant damping γ. Parameters ---------- omega_val : np.ndarray Array of angular frequency values ω(k) evaluated at discrete wavenumbers. Can be one-dimensional (1D) or two-dimensional (2D) depending on spatial dimension. Attributes Set -------------- - self.omega_val : np.ndarray Copy of the input angular frequency array. - self.cos_omega_dt : np.ndarray Cosine of ω(k) multiplied by time step: cos(ω(k) · dt). - self.sin_omega_dt : np.ndarray Sine of ω(k) multiplied by time step: sin(ω(k) · dt). - self.inv_omega_sin : np.ndarray Safe computation of sin(ω·dt)/ω using the sinc function: sin(ω·dt)/ω = dt·sinc(ω·dt/π), valid for all modes including ω=0. - self.inv_omega : np.ndarray Inverse of ω(k), with zeros where ω(k) == 0. - self.damp_p11, self.damp_p12, self.damp_p21, self.damp_p22 : np.ndarray Exact damped propagator matrix components for the linear part of second-order equations (u_tt + γ*u_t + ω²*u = 0), handling under-, critically, and over-damped modes via the sinc function. Reduces to cos/sin when γ = 0. Notes ----- - This method is typically called during setup when solving second-order PDEs involving dispersive waves (e.g., Klein-Gordon, Schrödinger, or water wave equations). - The computation of sin(ω·dt)/ω via the sinc function ensures numerical stability and correctness even when low frequencies (including ω=0) are present. """ self.omega_val = omega_val self.cos_omega_dt = np.cos(omega_val * self.dt) self.sin_omega_dt = np.sin(omega_val * self.dt) # Compute sin(ω·dt)/ω safely using sinc function # sinc(x) = sin(π·x)/(π·x), so sin(ω·dt)/ω = dt·sinc(ω·dt/π) z = omega_val * self.dt / np.pi self.inv_omega_sin = self.dt * np.sinc(z) # sin(ω·dt)/ω for all modes including ω=0 # Keep inv_omega for other uses, but handle zero mode properly self.inv_omega = np.zeros_like(omega_val) nonzero = omega_val != 0 self.inv_omega[nonzero] = 1.0 / omega_val[nonzero] self.inv_omega[~nonzero] = 0.0 # Will be handled by inv_omega_sin where needed # Exact propagator of u'' + gamma*u' + omega^2*u = 0 for each Fourier mode: # [u, v](dt) = [[p11, p12], [p21, p22]] [u, v](0) # valid for under-, critically and over-damped modes; for gamma = 0 it reduces to # cos/sin and includes the zero mode. g2 = 0.5 * self.damping wd = np.sqrt(np.asarray(omega_val, dtype=np.complex128) ** 2 - g2 ** 2) S = self.dt * np.sinc(wd * self.dt / np.pi) # sin(wd*dt)/wd (= dt when wd = 0) C = np.cos(wd * self.dt) E = np.exp(-g2 * self.dt) self.damp_p11 = np.real(E * (C + g2 * S)) self.damp_p12 = np.real(E * S) self.damp_p21 = -np.real(E * omega_val ** 2 * S) self.damp_p22 = np.real(E * (C - g2 * S)) def _precompile_source_funcs(self) -> None: """ Pre-compile lambdified callables for all source terms. Calling lambdify() inside the time loop (once per step) has a significant Python overhead. This method creates the callables once during setup and stores them in self._compiled_source_funcs so that the solve() loop can call them directly without rebuilding the function objects each iteration. Attributes set -------------- self._compiled_source_funcs : list[callable] One entry per source term. Each callable accepts (t, X[, Y]) where X and Y are the spatial grid arrays (numpy). """ self._compiled_source_funcs = [] if not hasattr(self, 'source_terms') or not self.source_terms: return # Stationary problems have no time variable: source terms are purely spatial # and are evaluated directly (not via lambdify with t). Skip pre-compilation # for those cases; solve_stationary_psiOp handles them on its own. if self.is_stationary or not hasattr(self, 't'): return for term in self.source_terms: try: if self.dim == 1: fn = lambdify((self.t, self.x), term, 'numpy') elif self.dim == 2: fn = lambdify((self.t, self.x, self.y), term, 'numpy') else: raise ValueError("Unsupported dimension in source pre-compilation.") self._compiled_source_funcs.append((fn, self.dim)) except Exception as e: print(f"Warning: could not pre-compile source term {term}: {e}") def _evaluate_source_at_t0(self) -> np.ndarray: """ Evaluate source terms at initial time t = 0 over the spatial grid. This private method computes the total contribution of all source terms at the initial time, evaluated across the entire spatial domain. It supports both one-dimensional (1D) and two-dimensional (2D) configurations. Returns ------- np.ndarray A numpy array representing the evaluated source term at t=0: - In 1D: Shape (Nx,), evaluated at each x in `self.x_grid`. - In 2D: Shape (Nx, Ny), evaluated at each (x, y) pair in the grid. Notes ----- - The symbolic expressions in `self.source_terms` are substituted with numerical values at t=0. - In 1D, each term is evaluated at (t=0, x=x_val). - In 2D, each term is evaluated at (t=0, x=x_val, y=y_val). - Evaluated using SymPy's `evalf()` to ensure numeric conversion. - This method assumes that the source terms have already been lambdified or are compatible with symbolic substitution. See Also -------- setup : Initializes the spatial grid and source terms. solve : Uses this evaluation during the first time step. """ if self.dim == 1: # Evaluation on the 1D spatial grid return np.array([ sum(term.subs(self.t, 0).subs(self.x, x_val).evalf() for term in self.source_terms) for x_val in self.x_grid ], dtype=np.complex128) else: # Evaluation on the 2D spatial grid return np.array([ [sum(term.subs({self.t: 0, self.x: x_val, self.y: y_val}).evalf() for term in self.source_terms) for y_val in self.y_grid] for x_val in self.x_grid ], dtype=np.complex128) def _initialize_conditions( self, initial_condition: Callable[..., np.ndarray], initial_velocity: Optional[Callable[..., np.ndarray]] = None ) -> None: """ Initialize the solution and velocity fields at t = 0. This private method sets up the initial state of the solution `u_prev` and, if applicable, the time derivative (velocity) `v_prev` for second-order evolution equations. For second-order equations, it also computes the backward-in-time value `u_prev2` needed by the Leap-Frog method. The acceleration at t = 0 is computed from: ∂ₜ²u = L(u) + N(u) + f(x, t=0) − γ ∂ₜu where L is the linear operator, N is the nonlinear term, f is the source term, and γ is the constant damping coefficient. Parameters ---------- initial_condition : callable Function returning the initial condition u(x, 0) or u(x, y, 0). initial_velocity : callable or None Function returning the initial velocity ∂ₜu(x, 0) or ∂ₜu(x, y, 0). Required for second-order equations; ignored otherwise. Raises ------ ValueError If `initial_velocity` is not provided for second-order equations. Notes ----- - Applies periodic boundary conditions after setting initial data. - Stores a copy of the initial state in `self.frames` for visualization/output. - In second-order systems, initializes `self.u_prev2` using a Taylor expansion: u_prev2 = u_prev - dt * v_prev + 0.5 * dt² * (∂ₜ²u) """ # Initial condition if self.dim == 1: self.u_prev = initial_condition(self.X) else: self.u_prev = initial_condition(self.X, self.Y) self._apply_boundary(self.u_prev) # Initial velocity (second order) if self.temporal_order == 2: if initial_velocity is None: raise ValueError("Initial velocity is required for second-order equations.") if self.dim == 1: self.v_prev = initial_velocity(self.X) else: self.v_prev = initial_velocity(self.X, self.Y) self.u0 = np.copy(self.u_prev) self.v0 = np.copy(self.v_prev) # Calculation of u_prev2 (initial acceleration) if not hasattr(self, 'u_prev2'): if self.has_psi: acc0 = -self._apply_psiOp(self.u_prev) else: acc0 = self._linear_rhs(self.u_prev, is_v=False) rhs_nl = self._apply_nonlinear(self.u_prev, is_v=False) acc0 += rhs_nl if hasattr(self, 'source_terms') and self.source_terms: acc0 += self._evaluate_source_at_t0() acc0 = acc0 - self.damping * self.v_prev self.u_prev2 = self.u_prev - self.dt * self.v_prev + 0.5 * self.dt**2 * acc0 self.frames = [self.u_prev.copy()] def _apply_boundary(self, u: np.ndarray) -> None: """ Heuristic post-hoc clipping of the boundary nodes (in place). - 'periodic': no-op (the FFT enforces periodicity natively). - 'nonperiodic' sets the boundary nodes to 0; the alias 'neumann' copies the interior neighbor. This is NOT a rigorous BVP enforcement; it is accurate only when the solution is negligible at the boundary. The relative size of the correction, max|Δu| / max|u|, is monitored: if it exceeds `self.boundary_tol`, a RuntimeWarning is issued once and the largest value seen is kept in `self._bc_max_correction`. Parameters ---------- u : np.ndarray Field on the spatial grid, shape (Nx,) or (Nx, Ny). Modified in place. Raises ------ ValueError If `self.boundary_condition` is not 'periodic', 'nonperiodic' or 'neumann'. """ bc = self.boundary_condition if bc == 'periodic': if self.periodic_edge_tol is not None: self._check_periodic_edge(u) return if bc != 'nonperiodic': raise ValueError(f"Invalid boundary condition '{bc}'. " "Supported types are 'periodic' and 'nonperiodic'.") before = u.copy() before = u.copy() if self._bc_clip == 'zero': # endpoint=False grid: node 0 is both x=-L/2 and its periodic image # x=+L/2, so zeroing it enforces BOTH walls. The last node # (x=L/2-h) is a free interior node and must not be clipped. if self.dim == 1: u[0] = 0 else: u[0, :] = 0 u[:, 0] = 0 else: # neumann if self.dim == 1: u[0] = u[1] u[-1] = u[-2] else: u[0, :] = u[1, :] u[-1, :] = u[-2, :] u[:, 0] = u[:, 1] u[:, -1] = u[:, -2] scale = max(float(np.max(np.abs(before))), np.finfo(float).tiny) corr = float(np.max(np.abs(u - before))) / scale self._bc_max_correction = max(self._bc_max_correction, corr) if corr > self.boundary_tol and not self._bc_warned: warnings.warn( f"'{bc}' clipping changed the solution by {corr:.2e} (relative) " f"at the boundary (> boundary_tol={self.boundary_tol:.1e}). " "The solution reaches the boundary: the clipping creates a jump " "in the periodic extension (Gibbs ringing). Enlarge the domain, " "use periodic BCs with a sponge layer, or the method of images.", RuntimeWarning, stacklevel=2, ) self._bc_warned = True def _check_periodic_edge(self, u: np.ndarray) -> None: """Warn (once) if the solution has non-negligible edge amplitude (wrap-around).""" if self.dim == 1: edge = np.concatenate((u[:1], u[-1:])) else: edge = np.concatenate((u[0, :], u[-1, :], u[:, 0], u[:, -1])) scale = max(float(np.max(np.abs(u))), np.finfo(float).tiny) amp = float(np.max(np.abs(edge))) / scale self._edge_max = max(self._edge_max, amp) if amp > self.periodic_edge_tol and not self._edge_warned: warnings.warn( f"Periodic solution reaches the box edge (relative amplitude " f"{amp:.2e} > periodic_edge_tol={self.periodic_edge_tol:.1e}): " "it wraps around the torus. Enlarge the domain, or add a sponge " "layer / use the method of images.", RuntimeWarning, stacklevel=2, ) self._edge_warned = True @staticmethod def _phi1(z: Union[np.ndarray, complex]) -> np.ndarray: """ Entire function φ₁(z) = (eᶻ − 1)/z, evaluated without 0/0 or cancellation near z = 0 (Taylor expansion 1 + z/2 + z²/6 for |z| < 1e-8). Works for scalars and arrays; always returns complex128. """ z = np.asarray(z, dtype=np.complex128) small = np.abs(z) < 1e-8 z_safe = np.where(small, 1.0, z) return np.where(small, 1.0 + z / 2.0 + z**2 / 6.0, np.expm1(z_safe) / z_safe) def _nonlinear_degree(self) -> Optional[int]: """ Polynomial degree of the nonlinear terms with respect to u and its derivatives (u and every ∂u are replaced by one generic variable). Returns 0 if there is no nonlinear term, and None if at least one term is not polynomial (sin(u), Abs(u), 1/(1+u), ...). """ from sympy import Dummy, Poly if not self.nonlinear_terms: return 0 s = Dummy('s') degree = 0 for term in self.nonlinear_terms: rep_map = {d: s for d in term.atoms(Derivative)} rep_map[self.u] = s try: degree = max(degree, Poly(term.xreplace(rep_map), s).degree()) except Exception: return None return degree @staticmethod def _get_diff_order(deriv: Derivative) -> Optional[Tuple[str, int]]: """ Normalise a SymPy Derivative atom to (variable_name, order) or None. Handles all known SymPy representations: Derivative(u(t, x), x) args[1] = Symbol('x') Derivative(u(t, x), (x, 2)) args[1] = sympy.Tuple(Symbol('x'), Integer(2)) Derivative(u(t, x), x, x) args[1] = args[2] = Symbol('x') Variable matching is done by name to avoid object-identity issues. Returns None for mixed derivatives. """ from sympy import Symbol, Tuple as SympyTuple variable_name = None order = 0 for arg in deriv.args[1:]: if isinstance(arg, (tuple, list, SympyTuple)): var_name = str(arg[0]) n = int(arg[1]) elif isinstance(arg, Symbol): var_name = arg.name n = 1 else: continue if variable_name is None: variable_name = var_name elif variable_name != var_name: return None # mixed derivative order += n if variable_name is None: return None return (variable_name, order) def _precompile_nonlinear_funcs(self) -> None: """ Pre-compile (once) the lambdified callables of all nonlinear terms. Each Derivative atom of u is replaced by a placeholder symbol (u_x, u_xx, u_xxx in 1D; u_x, u_y, u_xx, u_yy, u_xy in 2D) and the resulting expression is lambdified. `_apply_nonlinear` then only evaluates these callables, instead of rebuilding them at every call (4 times per step with ETD-RK4). Sets ---- self._compiled_nl : list[callable] 1D signature: f(t, x, u, u_x, u_xx, u_xxx) 2D signature: f(t, x, y, u, u_x, u_y, u_xx, u_yy, u_xy) """ from sympy import Tuple as SympyTuple self._compiled_nl = [] if self.is_stationary or not self.nonlinear_terms: return if self.dim == 1: x_name = self.x.name order_map = { (x_name, 1): symbols('u_x'), (x_name, 2): symbols('u_xx'), (x_name, 3): symbols('u_xxx'), } arg_names = (self.t, self.x, self.u_eq, 'u_x', 'u_xx', 'u_xxx') for term in self.nonlinear_terms: replacement = {} for deriv in term.atoms(Derivative): key = self._get_diff_order(deriv) if key is None: raise ValueError( f"Mixed derivative found in 1D nonlinear term: {deriv}." ) if key not in order_map: raise ValueError( f"Unsupported derivative in nonlinear term: {deriv}. " f"Resolved as order {key[1]} w.r.t. '{key[0]}'. " f"Supported: orders 1, 2, 3 w.r.t. '{x_name}'." ) replacement[deriv] = order_map[key] term_replaced = term.xreplace(replacement) if term_replaced.atoms(Derivative): raise ValueError( f"Incomplete derivative substitution in nonlinear term: {term}" ) self._compiled_nl.append(lambdify(arg_names, term_replaced, 'numpy')) elif self.dim == 2: x_name, y_name = self.x.name, self.y.name order_map = { (x_name, 1): symbols('u_x'), (y_name, 1): symbols('u_y'), (x_name, 2): symbols('u_xx'), (y_name, 2): symbols('u_yy'), } arg_names = (self.t, self.x, self.y, self.u_eq, 'u_x', 'u_y', 'u_xx', 'u_yy', 'u_xy') for term in self.nonlinear_terms: replacement = {} for deriv in term.atoms(Derivative): key = self._get_diff_order(deriv) if key is None: # Mixed derivative: only ∂x∂y (total order 2) is supported vars_in_deriv, total = set(), 0 for arg in deriv.args[1:]: if isinstance(arg, (tuple, list, SympyTuple)): vars_in_deriv.add(str(arg[0])) total += int(arg[1]) elif hasattr(arg, 'name'): vars_in_deriv.add(arg.name) total += 1 if vars_in_deriv == {x_name, y_name} and total == 2: replacement[deriv] = symbols('u_xy') else: raise ValueError( f"Unsupported mixed derivative in nonlinear term: {deriv}. " f"Variables found: {vars_in_deriv}, total order {total}. " f"Only ∂ₓᵧ is supported as a mixed derivative." ) elif key not in order_map: raise ValueError( f"Unsupported derivative in nonlinear term: {deriv}. " f"Resolved as order {key[1]} w.r.t. '{key[0]}'. " f"Supported: orders 1, 2 w.r.t. '{x_name}' or '{y_name}', " f"and mixed ∂ₓᵧ." ) else: replacement[deriv] = order_map[key] # xreplace: exact structural match, no silent misses unlike subs() term_replaced = term.xreplace(replacement) if term_replaced.atoms(Derivative): raise ValueError( f"Incomplete derivative substitution in nonlinear term.\n" f"Original term: {term}\n" f"Unresolved derivatives: {term_replaced.atoms(Derivative)}" ) self._compiled_nl.append(lambdify(arg_names, term_replaced, 'numpy')) else: raise ValueError( f"Unsupported spatial dimension: {self.dim}. Expected 1 or 2." ) def _apply_nonlinear( self, u: np.ndarray, is_v: bool = False, t: Optional[float] = None ) -> np.ndarray: """ Evaluate the nonlinear term N(u) of ∂ₜu = L u + N(u) + f (or of the second-order analogue), using spectral differentiation with dealiasing. The method returns the **rate N(u)**, NOT the increment Δt·N(u): the time integrators own the time weights (Δt, Δt·φ₁, Δt²/2, ETD-RK4 weights, RK4 weights, ...). Spatial derivatives appearing in the nonlinear expressions are obtained from the same dealiased spectrum û (mask applied to u before any product is formed), so only pointwise multiplications by (i·k)ⁿ and inverse FFTs are needed. **Derivative bank:** 1D: u_x, u_xx, u_xxx 2D: u_x, u_y, u_xx, u_yy, u_xy (u_xy = ∂ₓ∂ᵧu) The symbolic terms are lambdified once, in `_precompile_nonlinear_funcs` (called from `setup`; built lazily if needed). **Aliasing note:** The mask on the input is sufficient for quadratic terms with the 2/3 rule. For a polynomial of degree p, ratio 2/(p+1) is needed; `dealiasing_ratio=None` selects it automatically in `__init__`. **Velocity field variant:** When is_v=True, self.v_prev is used as the pointwise field value in the lambdified expressions; spectral derivatives are still computed from the argument u. Parameters ---------- u : numpy.ndarray Current solution on the spatial grid, (Nx,) in 1D or (Nx, Ny) in 2D. is_v : bool, optional (default False) If True, the pointwise field value is self.v_prev instead of u. t : float or None, optional Time at which N is evaluated (matters for explicit time dependence of N). If None, `self._t_current` is used (updated by `solve` at every step, 0.0 before). Returns ------- numpy.ndarray, dtype complex128 N(u) on the grid (same shape as u); zeros if there is no nonlinear term. Raises ------ ValueError If self.dim is neither 1 nor 2, or on unsupported derivatives (raised at pre-compilation). """ if not self.nonlinear_terms: return np.zeros_like(u, dtype=np.complex128) if getattr(self, '_compiled_nl', None) is None: self._precompile_nonlinear_funcs() if t is None: t = getattr(self, '_t_current', 0.0) nonlinear_term = np.zeros_like(u, dtype=np.complex128) if self.dim == 1: u_hat = self.fft(u) u_hat *= self.dealiasing_mask u = self.ifft(u_hat) # Derivative bank - all from the same dealiased û u_x = self.ifft((1j * self.KX) * u_hat) u_xx = self.ifft((1j * self.KX) ** 2 * u_hat) u_xxx = self.ifft((1j * self.KX) ** 3 * u_hat) field = self.v_prev if is_v else u for fn in self._compiled_nl: nonlinear_term += fn(t, self.X, field, u_x, u_xx, u_xxx) elif self.dim == 2: u_hat = self.fft(u) u_hat *= self.dealiasing_mask u = self.ifft(u_hat) # Derivative bank - all from the same dealiased û u_x = self.ifft((1j * self.KX) * u_hat) u_y = self.ifft((1j * self.KY) * u_hat) u_xx = self.ifft((1j * self.KX) ** 2 * u_hat) u_yy = self.ifft((1j * self.KY) ** 2 * u_hat) u_xy = self.ifft((1j * self.KX) * (1j * self.KY) * u_hat) u_phys = self.v_prev if is_v else u X, Y = self.X, self.Y def _eval_nl_term(fn): return fn(t, X, Y, u_phys, u_x, u_y, u_xx, u_yy, u_xy) if len(self._compiled_nl) >= 2: with ThreadPoolExecutor() as executor: for contrib in executor.map(_eval_nl_term, self._compiled_nl): nonlinear_term += contrib else: for fn in self._compiled_nl: nonlinear_term += _eval_nl_term(fn) else: raise ValueError( f"Unsupported spatial dimension: {self.dim}. Expected 1 or 2." ) return nonlinear_term def _prepare_symbol_tables(self) -> None: """ Precompute and store evaluated pseudo-differential operator symbols for spectral methods. This method evaluates the symbolic pseudo-differential operators (ψOp) on the spatial and frequency grids. It performs a fast vectorized conversion to complex128 arrays, bypassing per-element SymPy `N()` evaluation, and prepares the combined symbol for the Peetre backend or direct application. Attributes Set -------------- self.precomputed_symbols : list of tuple List of tuples containing the scalar coefficient and the evaluated complex128 array for each pseudo-differential operator. self.combined_symbol : np.ndarray The accumulated sum of all coefficient-weighted evaluated symbols, representing the total pseudo-differential operator on the grid. Notes ----- - This method is automatically called during `_setup_1D` or `_setup_2D` when pseudo-differential operators are present. - The vectorized accumulation is performed directly in NumPy memory for efficiency. """ self.precomputed_symbols = [] combined = None for coeff, psi in self.psi_ops: # Evaluate operator on spatial and frequency grids if self.dim == 1: raw = psi.evaluate(self.X, None, self.KX, None) elif self.dim == 2: raw = psi.evaluate(self.X, self.Y, self.KX, self.KY) else: raise ValueError('Unsupported spatial dimension.') # Fast vectorized conversion to complex128 array (bypassing per-element SymPy N() evaluation) if isinstance(raw, np.ndarray): raw_eval = raw.astype(np.complex128, copy=False) else: raw_eval = np.array(raw, dtype=np.complex128) # Convert the scalar coefficient explicitly (cheap: one N() call per operator, not per grid point) if not isinstance(coeff, (int, float, complex, np.number)): coeff_val = complex(N(coeff)) else: coeff_val = complex(coeff) self.precomputed_symbols.append((coeff_val, raw_eval)) # Vectorized accumulation directly in NumPy memory if combined is None: combined = np.zeros_like(raw_eval, dtype=np.complex128) combined += coeff_val * raw_eval self.combined_symbol = combined def _total_symbol_expr(self) -> Expr: """ Compute the total pseudo-differential symbol expression from all pseudo_terms. Constructs the full symbol of the pseudo-differential operator by summing up all coefficient-weighted symbolic expressions. The result is cached in `self.symbol_expr` to avoid recomputation. Returns ------- sympy.Expr The combined symbol expression, representing the full pseudo-differential operator in symbolic form. Examples -------- Given `pseudo_terms = [(2, ξ²), (1, x·ξ)]`, this returns `2·ξ² + x·ξ`. """ if not hasattr(self, '_symbol_expr'): self.symbol_expr = sum(coeff * expr for coeff, expr in self.pseudo_terms) return self.symbol_expr def _build_symbol_func(self, expr: Expr) -> Callable[..., np.ndarray]: """ Build a numerical evaluation function from a symbolic pseudo-differential operator expression. Converts a symbolic expression representing a pseudo-differential operator into a callable NumPy-compatible function. Parameters ---------- expr : sympy.Expr A SymPy expression representing the symbol of the pseudo-differential operator. It may depend on spatial variables (x, y) and frequency variables (ξ, η). Returns ------- callable A lambdified function that takes: - In 1D: `(x, ξ)` — spatial coordinate and frequency. - In 2D: `(x, y, ξ, η)` — spatial coordinates and frequencies. Returns a NumPy array of evaluated symbol values over input grids. Notes ----- - Uses `lambdify` from SymPy with the `'numpy'` backend for efficient vectorized evaluation. - Real variable assumptions are enforced to ensure proper behavior in numerical contexts. """ if self.dim == 1: x, xi = symbols('x xi', real=True) return lambdify((x, xi), expr, 'numpy') else: x, y, xi, eta = symbols('x y xi eta', real=True) return lambdify((x, y, xi, eta), expr, 'numpy') def _apply_psiOp( self, u: np.ndarray, psi_ops: Optional[List[Tuple[Any, Any]]] = None, is_spatial: Optional[bool] = None ) -> np.ndarray: """ Apply a pseudo-differential operator to the input field u. This method delegates to the apply() method of each PseudoDifferentialOperator. If the operators are configured with the Peetre backend, local and separable terms will automatically bypass the slow double-chunking integration and use fast global FFTs instead. For any remaining joint residuals that require the slow path, the underlying kohn_nirenberg_fft function already handles memory-bounded parallel row-blocking internally, so no outer ThreadPoolExecutor is needed here. """ if psi_ops is None: psi_ops = self.psi_ops if is_spatial is None: is_spatial = self.is_spatial if not psi_ops: raise ValueError("No pseudo-differential operators defined") result = np.zeros_like(u, dtype=np.complex128) for coeff, psi_op in psi_ops: coeff = np.complex128(coeff) if self.dim == 1: contribution = psi_op.apply( u=u, x_grid=self.x_grid, kx=self.kx, boundary_condition=self.boundary_condition, dealiasing_mask=self.dealiasing_mask, backend='peetre', joint_backend='direct', ) elif self.dim == 2: contribution = psi_op.apply( u=u, x_grid=self.x_grid, kx=self.kx, y_grid=self.y_grid, ky=self.ky, boundary_condition=self.boundary_condition, dealiasing_mask=self.dealiasing_mask, backend='peetre', joint_backend='direct', ) else: raise ValueError("Only 1D and 2D supported") result += coeff * contribution return result def _step_order1_with_psi(self, source_contribution: Union[np.ndarray, float, int]) -> np.ndarray: """ Perform one time step of a first-order evolution using a pseudo-differential operator. Updates the solution field using an exponential integrator scheme, depending on boundary conditions and the structure of the pseudo-differential symbol. Parameters ---------- source_contribution : np.ndarray or scalar Array representing the external source term at the current time step. Pass a scalar 0 to indicate no source; it will be broadcast to a zero array internally. Must match the spatial dimensions of `self.u_prev`. Returns ------- np.ndarray Updated solution array after one time step. Notes ----- The update follows three distinct computational paths: 1. Periodic boundaries + diagonalizable symbol: Exact Fourier-based exponential integrator. 2. Non-periodic boundaries + spatially uniform symbol: General ETD1 scheme in Fourier space. 3. Spatially varying symbol (Kohn-Nirenberg regime): Uses pointwise symbol as an approximate integrating factor, with a residual correction `R(uₙ) = L(uₙ) + σ·uₙ`. """ # Handling null source if np.isscalar(source_contribution): source = np.zeros_like(self.u_prev) else: source = source_contribution def _spectral_filter(u: np.ndarray, cutoff: float = 0.8) -> np.ndarray: if u.ndim == 1: u_hat = self.fft(u) N = len(u) k = fftfreq(N) mask = np.exp(-(k / cutoff)**8) return self.ifft(u_hat * mask).real elif u.ndim == 2: u_hat = self.fft(u) Ny, Nx = u.shape ky = fftfreq(Ny)[:, None] kx = fftfreq(Nx)[None, :] k_squared = kx**2 + ky**2 mask = np.exp(-(np.sqrt(k_squared) / cutoff)**8) return self.ifft(u_hat * mask).real else: raise ValueError("Only 1D and 2D arrays are supported.") # Recalculate symbol if necessary # if self.is_spatial: # self._prepare_symbol_tables() # Recalculates self.combined_symbol # Case with FFT (symbol diagonalizable in Fourier space) if self.boundary_condition == 'periodic' and not self.is_spatial: u_hat = self.fft(self.u_prev) u_hat *= np.exp(-self.dt * self.combined_symbol) u_hat *= self.dealiasing_mask u_symb = self.ifft(u_hat) u_nl = self._apply_nonlinear(self.u_prev) u_new = u_symb + self.dt * (u_nl + source) else: if self.boundary_condition == 'nonperiodic' and not self.is_spatial: # General case with ETD1 u_nl = self._apply_nonlinear(self.u_prev) # Calculation of exp(dt * L) and phi1(dt * L) L_vals = self.combined_symbol # Uses the updated symbol exp_L = np.exp(-self.dt * L_vals) # The linear part is -σ: φ₁(z) with z = -dt·σ phi1_L = self._phi1(-self.dt * L_vals) # Fourier transform u_hat = self.fft(self.u_prev) u_nl_hat = self.fft(u_nl) source_hat = self.fft(source) # Assembling the solution in Fourier space u_hat_new = exp_L * u_hat + self.dt * phi1_L * (u_nl_hat + source_hat) u_new = self.ifft(u_hat_new) else: Lu_prev = -self._apply_psiOp(self.u_prev) u_nl = self._apply_nonlinear(self.u_prev) # Use the symbol pointwise as an approximate integrating factor # This is exact when the symbol is spatially constant, and a good # approximation when it varies slowly — which is the Kohn-Nirenberg regime sigma = self.combined_symbol # shape matches u_prev exp_sigma = np.exp(-self.dt * sigma) phi1_sigma = np.where( np.abs(sigma) > 1e-10, (exp_sigma - 1.0) / (-self.dt * sigma), 1.0 ) # ETD1-like update using pointwise symbol (no extra _apply_psiOp call) # Lu_prev already incorporates the full nonlocal action; # the exponential factor corrects the linear stiffness locally u_new = exp_sigma * self.u_prev + self.dt * phi1_sigma * (u_nl + source) u_new += self.dt * phi1_sigma * (Lu_prev + sigma * self.u_prev) # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # correction: full L·u minus the diagonal approximation u_new = _spectral_filter(u_new, cutoff=self.dealiasing_ratio) return u_new def _step_order2_with_psi(self, source_contribution: np.ndarray) -> np.ndarray: """ Perform one time step of a second-order time evolution using a pseudo-differential operator. Updates the solution field using a damped second-order accurate leapfrog-style finite difference in time: uⁿ⁺¹ = [2uⁿ − (1 − g)uⁿ⁻¹ + Δt² ⋅ (L(uⁿ) + N(uⁿ) + F)] / (1 + g) where g = γ Δt / 2 (+ sponge contribution if active). Parameters ---------- source_contribution : np.ndarray Array representing the external source term at current time step. Must match the spatial dimensions of `self.u_prev`. Returns ------- np.ndarray Updated solution array after one time step. """ Lu_prev = -self._apply_psiOp(self.u_prev) rhs_nl = self._apply_nonlinear(self.u_prev, is_v=False) rhs = Lu_prev + rhs_nl + source_contribution g = 0.5 * self.damping * self.dt # gamma*dt/2 (u_tt + gamma*u_t = ...) if self.sponge_profile is not None: g = g + self.sponge_profile * self.dt # sponge (array) u_new = (2 * self.u_prev - (1 - g) * self.u_prev2 + self.dt ** 2 * rhs) / (1 + g) self._apply_boundary(u_new) self.u_prev2 = self.u_prev self.u_prev = u_new self.u = u_new return u_new
[docs] def solve(self) -> List[np.ndarray]: """ Solve the partial differential equation numerically using spectral methods. This method evolves the solution in time using a combination of Fourier-based linear evolution, nonlinear term handling via pseudo-spectral evaluation, and support for pseudo-differential operators (ψOp), source terms, and boundary conditions. Returns ------- list of np.ndarray A list of solution arrays at each saved time frame. Notes ----- - Updates `self.frames` to store solution snapshots. - Updates `self.energy_history` to record total energy if enabled. Algorithm Overview ------------------ For each time step: 1. Evaluate source contributions (if any). 2. Apply time evolution: - Order 1: Uses `_step_order1_with_psi`, ETD-RK4, or default linear+nonlinear update. - Order 2: Uses `_step_order2_with_psi` (damped leapfrog), ETD-RK4, or the exact damped exponential propagator (damp_pXX matrices) for the linear part when time_scheme != 'RK4'. 3. Enforce boundary conditions. 4. Save solution snapshot periodically. 5. Record energy (for second-order systems). """ print('\n*******************') print('* Solving the PDE *') print('*******************\n') save_interval = max(1, self.Nt // self.n_frames) self.energy_history = [] self.accumulated_work = 0.0 # RESET! self.mechanical_energy_history = [] self.work_history = [] self._prev_power = 0.0 # For trapezoidal rule for step in range(self.Nt): t_val = step * self.dt self._t_current = t_val # used by _apply_nonlinear source_contribution = self._eval_source(t_val) if self.temporal_order == 2: # Pass current time and source contribution E = self._compute_energy(t_val, source_contribution) self.energy_history.append(E) if self.temporal_order == 1: if self.has_psi: u_new = self._step_order1_with_psi(source_contribution) elif hasattr(self, 'time_scheme') and self.time_scheme == 'RK4': u_new = self._step_ETD_RK4_order1(self.u_prev, t_val) else: # Exponential Euler: # uⁿ⁺¹ = e^{LΔt} uⁿ + Δt φ₁(LΔt) (N(uⁿ) + fⁿ) u_hat = self.fft(self.u_prev) u_nl = self._apply_nonlinear(self.u_prev) rhs_hat = self.fft(u_nl + source_contribution) u_new_hat = self.exp_L * u_hat + self.dt * self.phi1_L * rhs_hat u_new_hat *= self.dealiasing_mask u_new = self.ifft(u_new_hat) # ── SPONGE DAMPING ── if self.sponge_profile is not None: u_new *= np.exp(-self.dt * self.sponge_profile) self._apply_boundary(u_new) self.u_prev = u_new elif self.temporal_order == 2: if self.has_psi: u_new = self._step_order2_with_psi(source_contribution) else: if hasattr(self, 'time_scheme') and self.time_scheme == 'RK4': u_new, v_new = self._step_RK4_order2(self.u_prev, self.v_prev, t_val) else: u_hat = self.fft(self.u_prev) v_hat = self.fft(self.v_prev) u_new_hat = self.damp_p11 * u_hat + self.damp_p12 * v_hat v_new_hat = self.damp_p21 * u_hat + self.damp_p22 * v_hat u_new = self.ifft(u_new_hat) v_new = self.ifft(v_new_hat) u_nl = self._apply_nonlinear(self.u_prev, is_v=False) u_new += (u_nl + source_contribution) * self.dt ** 2 / 2 v_new += (u_nl + source_contribution) * self.dt if self.sponge_profile is not None: damping = np.exp(-self.dt * self.sponge_profile) u_new *= damping v_new *= damping self._apply_boundary(u_new) self._apply_boundary(v_new) self.u_prev = u_new self.v_prev = v_new if (step + 1) % save_interval == 0: self.frames.append(self.u_prev.copy()) return self.frames
[docs] def solve_stationary_psiOp(self, order: int = 3) -> np.ndarray: """ Solve stationary pseudo-differential equations of the form P[u] = f(x) or P[u] = f(x,y) using asymptotic inversion. This method computes the solution to a stationary (time-independent) pseudo-differential equation where the operator P is defined via symbolic expressions (psiOp). It constructs an asymptotic right inverse R such that P∘R ≈ Id, then applies it to the source term f using either direct Fourier multiplication (when the symbol is spatially independent) or Kohn–Nirenberg quantization (when spatial dependence is present). The inversion is based on the principal symbol of the operator and its asymptotic expansion up to the given order. Ellipticity of the symbol is checked numerically before inversion to ensure well-posedness. Parameters ---------- order : int, default=3 Order of the asymptotic expansion used to construct the right inverse of the pseudo-differential operator. method : str, optional Inversion strategy: - 'diagonal' (default): Fast approximate inversion using diagonal operators in frequency space. - 'full' : Pointwise exact inversion (slower but more accurate). Returns ------- ndarray The computed solution u(x) in 1D or u(x, y) in 2D as a NumPy array over the spatial grid. Raises ------ ValueError If no pseudo-differential operator (psiOp) is defined. If linear or nonlinear terms other than psiOp are present. If the symbol is not elliptic on the grid. If no source term is provided for the right-hand side. Notes ----- - The method assumes the problem is fully stationary: time derivatives must be absent. - Requires the equation to be purely pseudo-differential (no Op, Derivative, or nonlinear terms). - Symbol evaluation and inversion are dimension-aware (supports both 1D and 2D problems). - Supports optimization paths when the symbol does not depend on spatial variables. See Also -------- right_inverse_asymptotic : Constructs the asymptotic inverse of the pseudo-differential operator. kohn_nirenberg : Numerical implementation of general pseudo-differential operators. is_elliptic_numerically : Verifies numerical ellipticity of the symbol. """ print("\n*******************************") print("* Solving the stationnary PDE *") print("*******************************\n") print("boundary condition: ",self.boundary_condition) if not self.has_psi: raise ValueError("Only supports problems with psiOp.") if self.linear_terms or self.nonlinear_terms: raise ValueError("Stationary psiOp problems must be linear and purely pseudo-differential.") if self.boundary_condition not in ('periodic', 'nonperiodic'): raise ValueError( "For stationary PDEs, boundary conditions must be explicitly defined. " "Supported types are 'periodic' and 'nonperiodic'." ) if self.dim == 1: x = self.x xi = symbols('xi', real=True) spatial_vars = (x,) freq_vars = (xi,) X, KX = self.X, self.KX elif self.dim == 2: x, y = self.x, self.y xi, eta = symbols('xi eta', real=True) spatial_vars = (x, y) freq_vars = (xi, eta) X, Y, KX, KY = self.X, self.Y, self.KX, self.KY else: raise ValueError("Unsupported spatial dimension.") total_symbol = sum(coeff * psi.expr for coeff, psi in self.psi_ops) psi_total = PseudoDifferentialOperator( total_symbol, spatial_vars, mode='symbol', apply_backend="peetre", # <--- Also optimize energy monitoring compute_peetre=True, ) # Check ellipticity if self.dim == 1: is_elliptic = psi_total.is_elliptic_numerically(X, KX) else: is_elliptic = psi_total.is_elliptic_numerically((X[:, 0], Y[0, :]), (KX[:, 0], KY[0, :])) if not is_elliptic: raise ValueError("❌ The pseudo-differential symbol is not numerically elliptic on the grid.") print("✅ Elliptic pseudo-differential symbol: inversion allowed.") R_symbol = psi_total.right_inverse_asymptotic(order=order) print('Right inverse asymptotic symbol:') pprint(R_symbol, num_columns=NUM_COLS) # ======================================================================== # FIX: Always lambdify with all variables for consistency # ======================================================================== if self.dim == 1: # Always include both x and xi in the signature R_func = lambdify((x, xi), R_symbol, modules='numpy') elif self.dim == 2: # Always include all four variables R_func = lambdify((x, y, xi, eta), R_symbol, modules='numpy') # Prepare right-hand side if self.source_terms: f_expr = sum(self.source_terms) used_vars = [v for v in spatial_vars if f_expr.has(v)] f_func = lambdify(used_vars, f_expr, modules='numpy') if self.dim == 1: rhs = f_func(self.x_grid) if used_vars else np.zeros_like(self.x_grid) else: rhs = f_func(self.X, self.Y) if used_vars else np.zeros_like(self.X) elif self.initial_condition: raise ValueError('Initial condition should be None for stationnary equation.') else: raise ValueError('No source term provided to construct the right-hand side.') f_hat = self.fft(rhs) # ======================================================================== # Application of the inverse operator via PseudoDifferentialOperator.apply # ======================================================================== R_op = PseudoDifferentialOperator( R_symbol, list(spatial_vars), mode="symbol", quantization="kohn-nirenberg", apply_backend = 'peetre', ) # If you have implemented apply_backend / use_peetre in PseudoDifferentialOperator, # and your global default is "peetre", you may want to force the direct path here # for the stationary inverse, unless you explicitly want Peetre acceleration. if hasattr(R_op, "apply_backend"): R_op.apply_backend = "direct" apply_kwargs = dict( boundary_condition=self.boundary_condition, dealiasing_mask=None, freq_window=None, # exact formal inverse, no frequency filtering clamp=np.inf, # no artificial clipping space_window=False, ) if self.dim == 1: u = R_op.apply( rhs, x_grid=self.x_grid, kx=self.kx, **apply_kwargs, ) elif self.dim == 2: u = R_op.apply( rhs, x_grid=self.x_grid, kx=self.kx, y_grid=self.y_grid, ky=self.ky, **apply_kwargs, ) else: raise ValueError("Unsupported spatial dimension.") self.u = u return u
def _eval_source(self, t_val: float) -> Union[np.ndarray, float]: """ Evaluate the total source term f(x,t) (or f(x,y,t)) at a given time `t_val`. This factors out the source-evaluation logic used in the main time-stepping loop so that sub-step schemes (e.g., ETD-RK4) can sample the source at the intermediate stage times they require (t, t+Δt/2, t+Δt, ...) instead of reusing a single value computed at the start of the step. Parameters ---------- t_val : float Time at which to evaluate the source term(s). Returns ------- np.ndarray or float Source contribution on the spatial grid, or 0.0 if no source terms are registered. """ if hasattr(self, '_compiled_source_funcs') and self._compiled_source_funcs: source = np.zeros_like(self.X, dtype=np.complex128) for fn, dim in self._compiled_source_funcs: try: if dim == 1: source += fn(t_val, self.X) elif dim == 2: source += fn(t_val, self.X, self.Y) except Exception as e: print(f'Error evaluating pre-compiled source term: {e}') return source else: return 0.0 def _etdrk4_coefficients(self, L_fft): """ Precompute the Cox–Matthews ETD-RK4 weights by the Kassam–Trefethen contour-integral trick, with memoisation. All weights are functions of the single dimensionless argument z = Δt·L(k), where L(k) is the Fourier symbol of the linear part. Written with the entire functions φ₁(z) = (eᶻ − 1)/z, φ₂(z) = (eᶻ − 1 − z)/z², φ₃(z) = (eᶻ − 1 − z − z²/2)/z³, the returned quantities are E = eᶻ, E2 = e^{z/2}, Q = Δt·(e^{z/2} − 1)/z = (Δt/2)·φ₁(z/2), f1 = Δt·(φ₁ − 3φ₂ + 4φ₃), f2 = Δt·(φ₂ − 2φ₃), f3 = Δt·(4φ₃ − φ₂), i.e. exactly the combinations used by `_step_ETD_RK4_order1`: a = E2·û + Q·N̂ᵤ, b = E2·û + Q·N̂ₐ, c = E2·â + Q·(2N̂_b − N̂ᵤ), ûⁿ⁺¹ = E·û + f1·N̂ᵤ + 2f2·(N̂ₐ + N̂_b) + f3·N̂_c. Each weight is evaluated as the mean of its defining expression over M = 32 points zz = z + rⱼ, rⱼ = exp(2iπ(j − ½)/M), j = 1…M, i.e. a circle of radius 1 centred at z, sampled at the half-offset roots of unity. Since the expressions are entire (their apparent poles at 0 are removable), the mean equals the value at the centre by Cauchy's formula, while never evaluating them at or near zz = 0. This removes the catastrophic cancellation of the direct formulas for |z| ≪ 1 (in particular at the zero mode k = 0) without any series branching. Parameters ---------- L_fft : numpy.ndarray Fourier symbol L(k) evaluated on the spectral grid, shape (Nx,) in 1D or (Nx, Ny) in 2D. May be complex (dispersive/advective symbols) or purely real (diffusive symbols). Returns ------- E, E2, Q, f1, f2, f3 : tuple of numpy.ndarray Arrays broadcastable to `L_fft.shape`. E and E2 are always complex; Q, f1, f2, f3 are cast to real when `L_fft` has identically zero imaginary part, so that diffusive problems stay in real arithmetic downstream. Notes ----- - The result is cached in `self._etd_coefs`; the associated key is stored in `self._etd_cache_key` and the symbol it was built from in `self._etd_L_fft_cache`. - The key is (Δt, shape, dtype, array_equal(L_fft, cached_symbol)). The last entry is a *boolean*, not a hash of the values: it detects that the symbol has changed, but the flag stored at rebuild time then differs from the flag computed at the next call, so the cache keeps alternating and the coefficients are effectively recomputed on every call once a change has occurred. To make the cache stable, drop the boolean from the key and compare `L_fft` with `_etd_L_fft_cache` separately. - Δt is read from `self.dt`; changing it (or the grid, hence the symbol) invalidates the cache through the key. - The contour radius is fixed to 1. Very large |z| (stiff symbols with large Δt) can overflow in exp(zz); no rescaling is attempted. - Cost: six exp evaluations on an array of size (…, 32), once per distinct configuration; memory peak is 32× the symbol array. References ---------- .. [1] Kassam, A.-K., & Trefethen, L. N. "Fourth-order time-stepping for stiff PDEs", SIAM J. Sci. Comput. 26(4), 1214–1233, 2005. .. [2] Cox, S. M., & Matthews, P. C. "Exponential time differencing for stiff systems", J. Comput. Phys. 176, 430–455, 2002. See Also -------- _step_ETD_RK4_order1 : The consumer of these weights (first-order PDEs). """ # Create a cache key based on current configuration cache_key = ( self.dt, L_fft.shape, L_fft.dtype, np.array_equal(L_fft, getattr(self, '_etd_L_fft_cache', None)) ) if getattr(self, '_etd_coefs', None) is None or getattr(self, '_etd_cache_key', None) != cache_key: dt = self.dt z = dt * L_fft M = 32 r = np.exp(2j * np.pi * (np.arange(1, M + 1) - 0.5) / M) zz = z[..., None] + r E, E2 = np.exp(z), np.exp(z / 2) Q = dt * np.mean((np.exp(zz / 2) - 1) / zz, axis=-1) f1 = dt * np.mean((-4 - zz + np.exp(zz) * (4 - 3 * zz + zz**2)) / zz**3, axis=-1) f2 = dt * np.mean((2 + zz + np.exp(zz) * (-2 + zz)) / zz**3, axis=-1) f3 = dt * np.mean((-4 - 3 * zz - zz**2 + np.exp(zz) * (4 - zz)) / zz**3, axis=-1) if np.max(np.abs(np.imag(L_fft))) == 0: # real L (diffusion): coefficients are real Q, f1, f2, f3 = (c.real for c in (Q, f1, f2, f3)) self._etd_coefs = (E, E2, Q, f1, f2, f3) self._etd_cache_key = cache_key self._etd_L_fft_cache = L_fft.copy() return self._etd_coefs def _step_ETD_RK4_order1(self, u: np.ndarray, t: float = 0.0) -> np.ndarray: """ Perform one Exponential Time Differencing Runge-Kutta 4th-order (ETD-RK4) time step for first-order in time PDEs, using the Kassam–Trefethen scheme. Solves equations of the form: ∂ₜu = L·u + N(u) + f(x,t) where L is a linear operator (diagonal in Fourier space) and N is a nonlinear term treated via pseudo-spectral methods. Let G(v, τ) = N(v) + f(τ). The scheme exactly integrates the linear part and uses a 4-stage Runge-Kutta approximation for G: a = exp(dt/2·L)·uₙ + Q·G(uₙ, tₙ) b = exp(dt/2·L)·uₙ + Q·G(a, tₙ + dt/2) c = exp(dt/2·L)·a + Q·[2·G(b, tₙ + dt/2) - G(uₙ, tₙ)] uₙ₊₁ = exp(dt·L)·uₙ + f₁·G(uₙ, tₙ) + 2·f₂·[G(a, tₙ + dt/2) + G(b, tₙ + dt/2)] + f₃·G(c, tₙ + dt) The weights Q, f₁, f₂, f₃ correspond to dt·φₖ(dt·L) or dt·φₖ(dt/2·L): Q = dt·φ₁(dt/2·L) f₁ = dt·φ₁(dt·L) f₂ = dt·φ₂(dt·L) f₃ = dt·φ₃(dt·L) where the entire functions φₖ(z) are defined as: φ₁(z) = (eᶻ - 1) / z φ₂(z) = (eᶻ - 1 - z) / z² φ₃(z) = (eᶻ - 1 - z - z²/2) / z³ To avoid numerical cancellation (0/0) near z = 0, these coefficients are computed using a 32-point Cauchy contour integral in the complex plane. Parameters ---------- u : np.ndarray Current solution in real space (physical grid values). t : float, optional Current time. Default is 0.0. Returns ------- np.ndarray Updated solution in real space after one ETD-RK4 time step. Notes ----- - The linear part L is diagonal in Fourier space and precomputed as `self.L(k)`. - Nonlinear terms and source terms are evaluated in physical space and transformed via FFT. - The source term f(x,t) is treated as part of the non-autonomous nonlinear term and sampled at the stage times t, t + dt/2, and t + dt. - Assumes periodic boundary conditions and uses spectral differentiation via FFT. See Also -------- _step_RK4_order2 : Explicit RK4 for second-order in time equations. _etdrk4_coefficients : Computation of the ETD-RK4 weights via contour integration. _apply_nonlinear : For handling nonlinear terms in the PDE. References ---------- .. [1] Kassam, A.-K., & Trefethen, L. N. (2005). Fourth-order time-stepping for stiff PDEs. SIAM Journal on Scientific Computing, 26(4), 1214-1233. """ dt = self.dt L_fft = self.L(self.KX) if self.dim == 1 else self.L(self.KX, self.KY) E, E2, Q, f1, f2, f3 = self._etdrk4_coefficients(L_fft) fft, ifft = self.fft, self.ifft s0 = self._eval_source(t) sh = self._eval_source(t + 0.5 * dt) s1 = self._eval_source(t + dt) nl = lambda v, tau: self._apply_nonlinear(v, t=tau) # N(v) at time tau u_hat = fft(u) Nu = fft(nl(u, t) + s0) a = ifft(E2 * u_hat + Q * Nu) Na = fft(nl(a, t + 0.5 * dt) + sh) b = ifft(E2 * u_hat + Q * Na) Nb = fft(nl(b, t + 0.5 * dt) + sh) c = ifft(E2 * fft(a) + Q * (2 * Nb - Nu)) Nc = fft(nl(c, t + dt) + s1) return ifft(E * u_hat + f1 * Nu + 2 * f2 * (Na + Nb) + f3 * Nc) def _step_RK4_order2(self, u: np.ndarray, v: np.ndarray, t: float = 0.0) -> Tuple[np.ndarray, np.ndarray]: """ Perform one time step using explicit 4th-order Runge-Kutta for second-order PDEs. Advances the solution of ∂ₜ²u + γ ∂ₜu = L·u + N(u) + f(x,t) by rewriting it as a first-order system: ∂ₜu = v ∂ₜv = L·u + N(u) + f(x,t) − γ v and applying the classical 4-stage Runge-Kutta method. Parameters ---------- u : np.ndarray Current solution array in real space. v : np.ndarray Current time derivative ∂ₜu in real space. t : float, optional Current time. Default is 0.0. Returns ------- tuple of np.ndarray (u_new, v_new): Updated solution and velocity after one time step. Notes ----- This is an explicit integrator subject to CFL stability restrictions Δt ∝ Δx^(m/2), where m is the order of the linear operator L. For stiff operators, consider using exponential time differencing schemes (e.g., `step_ETD_RK4_order1` for first-order equations). The linear operator L is applied spectrally via FFT, and nonlinear terms are evaluated in physical space using the pseudo-spectral method with dealiasing. """ dt = self.dt L_fft = self.L(self.KX) if self.dim == 1 else self.L(self.KX, self.KY) fft = self.fft ifft = self.ifft gamma = self.damping # u_tt + gamma*u_t = L u + N(u) + f def rhs(u_val, v_val, t_val): return (ifft(L_fft * fft(u_val)) + self._apply_nonlinear(u_val, is_v=False, t=t_val) + self._eval_source(t_val) - gamma * v_val) # Stage A (t) A = rhs(u, v, t) ua = u + 0.5 * dt * v va = v + 0.5 * dt * A # Stage B (t + dt/2) B = rhs(ua, va, t + 0.5 * dt) ub = u + 0.5 * dt * va vb = v + 0.5 * dt * B # Stage C (t + dt/2) C = rhs(ub, vb, t + 0.5 * dt) uc = u + dt * vb vc = v + dt * C # Stage D (t + dt) D = rhs(uc, vc, t + dt) # Final update (correct RK4 weights for 2nd order system) u_new = u + dt * v + (dt**2 / 6.0) * (A + B + C) v_new = v + (dt / 6.0) * (A + 2*B + 2*C + D) return u_new, v_new def _check_cfl_condition(self) -> None: """ Check the CFL (Courant–Friedrichs–Lewy) condition for numerical stability. Verifies whether the chosen time step Δt satisfies the stability condition derived from the maximum wave propagation speed in the system. The maximum speed is computed from the group velocity of the dispersion relation. Notes ----- **Second-order equations** (∂ₜ²u = L u + N(u) + f): Uses the group velocity v_g(k) = dω/dk from the dispersion relation ω(k). The maximum wave speed is max|v_g(k)|. **First-order equations** (∂ₜu = L u + N(u) + f): The dispersion relation is ω(k) = -i·L(k). The group velocity is v_g(k) = dω/dk = -i·dL/dk. - For purely advective equations (Re(L) = 0): uses v_g = d(Im(ω))/dk - For dissipative or mixed equations: uses phase velocity |Im(L)/k| as an upper bound on characteristic speed **Dimensionality**: - 1D: Evaluates group velocity along the single spatial direction - 2D: Evaluates group velocities independently in x and y directions, then combines as 1/(v_x/Δx + v_y/Δy) **Safety factor**: Uses a conservative safety factor of 0.5, so the reported CFL limit is Δt_max = 0.5 · Δx / max_speed (1D) or the 2D equivalent. Raises ------ NotImplementedError If the spatial dimension is not 1D or 2D. Examples -------- For the advection equation ∂ₜu + c·∂ₓu = 0, we have L(k) = -i·c·k, so ω(k) = c·k and v_g = c. The CFL condition becomes Δt ≤ 0.5·Δx/|c|. For the wave equation ∂ₜ²u = c²·∂ₓₓu, we have ω(k) = c·|k| and v_g = c·sign(k), so Δt ≤ 0.5·Δx/c. """ print("\n*****************") print("* CFL condition *") print("*****************\n") cfl_factor = 0.5 # Safety factor if self.dim == 1: if self.temporal_order == 2 and hasattr(self, 'omega'): # Second order: use group velocity from dispersion relation k_vals = self.kx omega_vals = np.real(self.omega(k_vals)) with np.errstate(divide='ignore', invalid='ignore'): v_group = np.gradient(omega_vals, k_vals) max_speed = np.max(np.abs(v_group)) elif self.temporal_order == 1: # First order: compute group velocity from dispersion relation # For ∂ₜu = L·u, the dispersion relation is ω = -i·L(k) k_vals = self.kx L_vals = self.L(k_vals) omega_vals = -1j * L_vals # ω(k) = -i·L(k) # Group velocity: v_g = dω/dk = -i·dL/dk with np.errstate(divide='ignore', invalid='ignore'): dL_dk = np.gradient(L_vals, k_vals) v_group = -1j * dL_dk # For stability, we need the maximum characteristic speed # For advective equations (L purely imaginary), this is |Im(ω)/k| # For dissipative equations (L has real part), use the imaginary part if np.allclose(np.real(L_vals), 0): # Purely advective: v_g = d(Im(ω))/dk max_speed = np.max(np.abs(np.real(v_group))) else: # Mixed or dissipative: use phase velocity as upper bound with np.errstate(divide='ignore', invalid='ignore'): v_phase = np.abs(np.imag(L_vals) / k_vals) v_phase[k_vals == 0] = 0 max_speed = np.max(v_phase) else: # Fallback max_speed = np.max(np.abs(np.imag(self.L(self.kx)))) dx = self.Lx / self.Nx cfl_limit = cfl_factor * dx / max_speed if max_speed != 0 else np.inf if self.dt > cfl_limit: print(f"⚠️ CFL condition violated: dt = {self.dt:.4e}, max allowed dt = {cfl_limit:.4e}") else: print(f"✅ CFL condition satisfied: dt = {self.dt:.4e} ≤ {cfl_limit:.4e}") elif self.dim == 2: # Similar corrections for 2D... if self.temporal_order == 2 and hasattr(self, 'omega'): k_vals = self.kx omega_x = np.real(self.omega(k_vals, 0)) omega_y = np.real(self.omega(0, k_vals)) with np.errstate(divide='ignore', invalid='ignore'): v_group_x = np.gradient(omega_x, k_vals) v_group_y = np.gradient(omega_y, k_vals) max_speed_x = np.max(np.abs(v_group_x)) max_speed_y = np.max(np.abs(v_group_y)) else: # First order or fallback max_speed_x = np.max(np.abs(np.imag(self.L(self.kx, 0)))) max_speed_y = np.max(np.abs(np.imag(self.L(0, self.ky)))) dx = self.Lx / self.Nx dy = self.Ly / self.Ny cfl_limit = cfl_factor / (max_speed_x / dx + max_speed_y / dy) if (max_speed_x + max_speed_y) != 0 else np.inf if self.dt > cfl_limit: print(f"⚠️ CFL condition violated: dt = {self.dt:.4e}, max allowed dt = {cfl_limit:.4e}") else: print(f"✅ CFL condition satisfied: dt = {self.dt:.4e} ≤ {cfl_limit:.4e}") else: raise NotImplementedError("Only 1D and 2D problems are supported.") def _check_symbol_conditions( self, k_range: Optional[Tuple[float, float, int]] = None, verbose: bool = True ) -> None: """ Check strict analytic conditions on the linear symbol `self.L_symbolic`. Evaluates three key properties of the Fourier multiplier symbol a(k) = self.L(k), which are crucial for well-posedness, stability, and numerical efficiency. Parameters ---------- k_range : tuple or None, optional Specifies the range of frequencies to test in the form `(k_min, k_max, N)`. If None, defaults are used: `[-10, 10]` with 500 points in 1D, or `[-10, 10]` with 100 points per axis in 2D. verbose : bool, default=True If True, prints detailed results of each condition check. Returns ------- None Output is printed directly to the console for interpretability. Notes ----- - **Stability condition**: Re(a(k)) ≤ 0 for all k ≠ 0. - **Dissipation condition**: Re(a(k)) ≤ -δ |k|² for large |k|. - **Growth condition**: |a(k)| ≤ C (1 + |k|)^m with m ≤ 4. - In 2D, the radial frequency |k| = √(kx² + ky²) is used for comparisons. See Also -------- _analyze_wave_propagation : For further symbolic and numerical analysis of dispersion. _plot_symbol : Visualizes the symbol's behavior over the frequency domain. """ print("\n********************") print("* Symbol condition *") print("********************\n") if self.dim == 1: if k_range is None: k_vals = np.linspace(-10, 10, 500) else: k_min, k_max, N = k_range k_vals = np.linspace(k_min, k_max, N) L_vals = self.L(k_vals) k_abs = np.abs(k_vals) elif self.dim == 2: if k_range is None: k_vals = np.linspace(-10, 10, 100) else: k_min, k_max, N = k_range k_vals = np.linspace(k_min, k_max, N) KX, KY = np.meshgrid(k_vals, k_vals) L_vals = self.L(KX, KY) k_abs = np.sqrt(KX**2 + KY**2) else: raise ValueError("Only 1D and 2D dimensions are supported.") re_vals = np.real(L_vals) abs_vals = np.abs(L_vals) # === Condition 1: Stability if np.any(re_vals > 1e-12): max_pos = np.max(re_vals) if verbose: print(f"❌ Stability violated: max Re(a(k)) = {max_pos}") print("Unstable symbol: Re(a(k)) > 0") elif verbose: print("✅ Spectral stability satisfied: Re(a(k)) ≤ 0") # === Condition 2: Dissipation mask = k_abs > 2 if np.any(mask): re_decay = re_vals[mask] expected_decay = -0.01 * k_abs[mask]**2 if np.any(re_decay > expected_decay + 1e-6): if verbose: print("⚠️ Insufficient high-frequency dissipation") else: if verbose: print("✅ Proper high-frequency dissipation") # === Condition 3: Growth growth_ratio = abs_vals / (1 + k_abs)**4 if np.max(growth_ratio) > 100: if verbose: print("⚠️ Symbol grows rapidly: |a(k)| ≳ |k|^4") else: if verbose: print("✅ Reasonable spectral growth") if verbose: print("✔ Symbol analysis completed.") def _analyze_wave_propagation(self) -> None: """ Perform a detailed analysis of wave propagation characteristics based on the dispersion relation ω(k). Visualizes key wave properties in both 1D and 2D settings: - Dispersion relation: ω(k) - Phase velocity: vₚ(k) = ω(k)/|k| - Group velocity: v₉(k) = ∇ₖ ω(k) Notes ----- - The symbolic dispersion relation `omega_symbolic` must be defined beforehand. - In 1D: Plots ω(k), vₚ(k), and v₉(k) over a range of k values. - In 2D: Displays heatmaps of ω(kx, ky), vₚ(kx, ky), and |v₉(kx, ky)|. - Generates and displays matplotlib plots as a side effect. Raises ------ AttributeError If `omega_symbolic` is not defined, the method exits gracefully with a message. """ print("\n*****************************") print("* Wave propagation analysis *") print("*****************************\n") if not hasattr(self, 'omega_symbolic'): print("❌ omega_symbolic not defined. Only available for 2nd order in time.") return if self.dim == 1: k = self.k_symbols[0] omega_func = lambdify(k, self.omega_symbolic, 'numpy') k_vals = np.linspace(-10, 10, 1000) omega_vals = omega_func(k_vals) with np.errstate(divide='ignore', invalid='ignore'): v_phase = np.where(k_vals != 0, omega_vals / k_vals, 0.0) dk = k_vals[1] - k_vals[0] v_group = np.gradient(omega_vals, dk) plt.figure(figsize=(10, 6)) plt.plot(k_vals, omega_vals, label=r'$\omega(k)$') plt.plot(k_vals, v_phase, label=r'$v_p(k)$') plt.plot(k_vals, v_group, label=r'$v_g(k)$') plt.title("1D Wave Propagation Analysis") plt.xlabel("k") plt.grid() plt.legend() plt.tight_layout() plt.show() elif self.dim == 2: kx, ky = self.k_symbols omega_func = lambdify((kx, ky), self.omega_symbolic, 'numpy') k_vals = np.linspace(-10, 10, 200) KX, KY = np.meshgrid(k_vals, k_vals) K_mag = np.sqrt(KX**2 + KY**2) K_mag[K_mag == 0] = 1e-8 # Avoid division by 0 omega_vals = omega_func(KX, KY) v_phase = np.real(omega_vals) / K_mag dk = k_vals[1] - k_vals[0] domega_dx = np.gradient(omega_vals, dk, axis=0) domega_dy = np.gradient(omega_vals, dk, axis=1) v_group_norm = np.sqrt(np.abs(domega_dx)**2 + np.abs(domega_dy)**2) fig, axs = plt.subplots(1, 3, figsize=(18, 5)) im0 = axs[0].imshow(np.real(omega_vals), extent=[-10, 10, -10, 10], origin='lower', cmap='viridis') axs[0].set_title(r'$\omega(k_x, k_y)$') plt.colorbar(im0, ax=axs[0]) im1 = axs[1].imshow(v_phase, extent=[-10, 10, -10, 10], origin='lower', cmap='plasma') axs[1].set_title(r'$v_p(k_x, k_y)$') plt.colorbar(im1, ax=axs[1]) im2 = axs[2].imshow(v_group_norm, extent=[-10, 10, -10, 10], origin='lower', cmap='inferno') axs[2].set_title(r'$|v_g(k_x, k_y)|$') plt.colorbar(im2, ax=axs[2]) for ax in axs: ax.set_xlabel(r'$k_x$') ax.set_ylabel(r'$k_y$') ax.set_aspect('equal') plt.tight_layout() plt.show() else: print("❌ Only 1D and 2D wave analysis supported.") def _plot_symbol( self, component: str = "abs", k_range: Optional[Tuple[float, float, int]] = None, cmap: str = "viridis" ) -> None: """ Visualize the spectral symbol L(k) or L(kx, ky) in 1D or 2D. Plots the linear operator's symbolic Fourier representation either as a function of a single wavenumber k (1D), or two wavenumbers kx and ky (2D). Parameters ---------- component : str {'abs', 're', 'im'} Component of the symbol to visualize: - 'abs' : absolute value |a(k)| - 're' : real part Re[a(k)] - 'im' : imaginary part Im[a(k)] k_range : tuple (kmin, kmax, N), optional Wavenumber range for evaluation. If None, defaults to `[-10, 10]` with high resolution. cmap : str, optional Colormap used for 2D surface plots. Default is 'viridis'. Raises ------ ValueError If the spatial dimension is not 1D or 2D. Notes ----- - In 1D, the symbol is plotted using a standard 2D line plot. - In 2D, a 3D surface plot is generated with color-mapped height. """ print("\n*******************") print("* Symbol plotting *") print("*******************\n") assert component in ("abs", "re", "im"), "component must be 'abs', 're' or 'im'" if self.dim == 1: if k_range is None: k_vals = np.linspace(-10, 10, 1000) else: kmin, kmax, N = k_range k_vals = np.linspace(kmin, kmax, N) L_vals = self.L(k_vals) if component == "re": vals = np.real(L_vals) label = "Re[a(k)]" elif component == "im": vals = np.imag(L_vals) label = "Im[a(k)]" else: vals = np.abs(L_vals) label = "|a(k)|" plt.plot(k_vals, vals) plt.xlabel("k") plt.ylabel(label) plt.title(f"Spectral symbol: {label}") plt.grid(True) plt.show() elif self.dim == 2: if k_range is None: k_vals = np.linspace(-10, 10, 300) else: kmin, kmax, N = k_range k_vals = np.linspace(kmin, kmax, N) KX, KY = np.meshgrid(k_vals, k_vals) L_vals = self.L(KX, KY) if component == "re": Z = np.real(L_vals) title = "Re[a(kx, ky)]" elif component == "im": Z = np.imag(L_vals) title = "Im[a(kx, ky)]" else: Z = np.abs(L_vals) title = "|a(kx, ky)|" fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') surf = ax.plot_surface(KX, KY, Z, cmap=cmap, edgecolor='none', antialiased=True) fig.colorbar(surf, ax=ax, shrink=0.6) ax.set_xlabel("kx") ax.set_ylabel("ky") ax.set_zlabel(title) ax.set_title(f"2D spectral symbol: {title}") plt.tight_layout() plt.show() else: raise ValueError("Only 1D and 2D supported.") def _compute_energy( self, t_val: float, source_contribution: Union[np.ndarray, float, int] = 0.0 ) -> Optional[float]: """ Compute the total (conserved) energy of the system at time `t_val`. For a second-order evolution ∂ₜ²u = L·u + N(u) + f(x,t), the mechanical energy is split into a kinetic part and a linear-potential part, while the work done by the non-conservative terms (N, f) is accumulated separately so that a conserved quantity can be monitored: E_mech(t) = Eₖ(t) + Eₚ(t) W(t) = ∫₀ᵗ ⟨v, N(u) + f⟩ dx dt' (trapezoidal rule) E_total(t) = E_mech(t) − W(t) ← conserved Note: The work done by the constant damping force (−γ v) is NOT tracked in the accumulated work W(t). Consequently, the "Total Conserved Energy" E_total(t) will exhibit a systematic drift corresponding to the energy dissipated by the damping term. Parameters ---------- t_val : float Current simulation time. source_contribution : np.ndarray or float, optional Source term f(x,t) evaluated on the spatial grid at time `t_val`. A scalar or `None` is treated as zero. Returns ------- float or None The conserved energy E_total(t) = E_mech(t) − W(t), or `None` if the problem is not second-order in time or the required state is not yet initialised. Side effects ------------ - Appends `E_mech` to `self.mechanical_energy_history`. - Appends `W(t)` to `self.work_history`. - Updates `self._prev_power` for the next trapezoidal increment. - On first call with nonlinear or source terms, prints a one-time warning that energy monitoring tracks the work balance. """ if self.temporal_order != 2: return None # Warning for nonlinear/source terms (once) if not getattr(self, '_energy_warning_issued', False): if self.nonlinear_terms or self.source_terms: print("⚠️ Warning: Energy monitoring includes work from nonlinear/source terms.") self._energy_warning_issued = True u = self.u_prev dx = self.Lx / self.Nx dy = self.Ly / self.Ny if self.dim > 1 else 1.0 # 1. Compute Velocity and Potential Operator Terms Consistent with Physics if self.has_psi: if self.u_prev2 is None: return None # Centered difference for velocity when using staggered states v = (self.u_prev - self.u_prev2) / self.dt if not hasattr(self, '_energy_psi_op'): return None # For psi_op path, Lu already represents the correct square-root potential mapped state Lu = self._apply_psiOp( u, psi_ops=[(1, self._energy_psi_op)], is_spatial=self._energy_is_spatial ) pot_density = 0.5 * np.abs(Lu)**2 else: if self.v_prev is None: return None v = self.v_prev # Compute potential energy via Fourier representation u_hat = self.fft(u) L_vals = self.L(self.KX) if self.dim == 1 else self.L(self.KX, self.KY) # For well-posed 2nd order equations, L should be negative definite # (e.g., L = -k² for wave equation, L = -k⁴ for beam equation) # The potential energy operator is -L, which should be positive minus_L = -np.real(L_vals) # Take real part and negate # Check if the operator is indeed negative definite if np.any(minus_L < -1e-10): warnings.warn( "Linear operator L is not negative definite. " "Energy computation may be incorrect.", RuntimeWarning ) # Ensure positivity for safety minus_L = np.maximum(minus_L, 0.0) # Compute potential energy density Lu_pot = self.ifft(minus_L * u_hat) pot_density = 0.5 * np.real(u * np.conj(Lu_pot)) # 2. Compute Total Mechanical Energy kin_density = 0.5 * np.abs(v)**2 energy_density = kin_density + pot_density if self.dim == 1: E_mech = np.sum(energy_density) * dx else: E_mech = np.sum(energy_density) * dx * dy # 3. Compute Instantaneous Power: P = ∫ v · (N(u) + f) dx N_u = self._apply_nonlinear(self.u_prev, is_v=False) if source_contribution is None or np.isscalar(source_contribution): f = np.zeros_like(u) else: f = source_contribution power_density = np.real(v * np.conj(N_u + f)) if self.dim == 1: power = np.sum(power_density) * dx else: power = np.sum(power_density) * dx * dy # 4. Accumulate Work via Trapezoidal Rule if not hasattr(self, '_prev_power'): self._prev_power = power work_increment = 0.5 * (self._prev_power + power) * self.dt self.accumulated_work += work_increment self._prev_power = power # Store histories self.mechanical_energy_history.append(E_mech) self.work_history.append(self.accumulated_work) # Total conserved energy E_total = E_mech - self.accumulated_work return E_total def _plot_sponge_profile(self) -> None: """Plot the sponge damping profile for verification.""" if self.sponge_profile is None: return if self.dim == 1: plt.figure(figsize=(10, 3)) plt.plot(self.x_grid, self.sponge_profile, 'r-', linewidth=2) plt.xlabel('x') plt.ylabel('γ(x)') plt.title('Sponge damping profile') plt.axvspan(-self.Lx/2, -self.Lx/2*(1-self.sponge_width), alpha=0.1, color='red') plt.axvspan(self.Lx/2*(1-self.sponge_width), self.Lx/2, alpha=0.1, color='red') plt.grid(True) plt.tight_layout() plt.show() elif self.dim == 2: plt.figure(figsize=(6, 5)) plt.imshow(self.sponge_profile, origin='lower', cmap='hot', extent=[-self.Lx/2, self.Lx/2, -self.Ly/2, self.Ly/2]) plt.colorbar(label='γ(x, y)') plt.xlabel('x') plt.ylabel('y') plt.title('2D Sponge damping profile') plt.tight_layout() plt.show()
[docs] def plot_energy(self, log: bool = False) -> None: """ Plot the temporal evolution of energy components and print conservation diagnostics. Generates a 3-panel subplot tracking: 1. Mechanical Energy: Eₘₑ꜀ₕ(t) = Eₖ(t) + Eₚ(t) 2. Accumulated Work: W(t) = ∫₀ᵗ ⟨∂ₜu, f⟩ dx 3. Total Conserved Energy: Eₜₒₜₐₗ(t) = Eₘₑ꜀ₕ(t) - W(t) Prints the initial total energy E₀ and the maximum relative drift: Relative Drift = max |Eₜₒₜₐₗ(t) - E₀| / |E₀| Parameters ---------- log : bool, optional If True, plots the total conserved energy using a logarithmic y-axis (semilogy). Default is False. """ if not hasattr(self, 'energy_history') or not self.energy_history or not self.compute_energy: print("No energy data recorded.") return t = np.linspace(0, self.Lt, len(self.energy_history)) plt.figure(figsize=(10, 9)) if hasattr(self, 'mechanical_energy_history'): plt.subplot(3, 1, 1) plt.plot(t, self.mechanical_energy_history, color='blue') plt.ylabel('Mechanical Energy') plt.title('Mechanical Energy (Oscillates/Grows due to terms)') plt.grid(True) if hasattr(self, 'work_history'): plt.subplot(3, 1, 2) plt.plot(t, self.work_history, color='orange') plt.ylabel('Accumulated Work') plt.title('Accumulated Work (Energy injected/extracted by terms)') plt.grid(True) plt.subplot(3, 1, 3) if log: plt.semilogy(t, self.energy_history, color='green', linewidth=2) else: plt.plot(t, self.energy_history, color='green', linewidth=2) plt.xlabel('Time') plt.ylabel('Total Energy') plt.title(r'Total Conserved Energy $E_{\mathrm{mech}} - W$') plt.grid(True) plt.tight_layout() plt.show() E0 = self.energy_history[0] drift = np.max(np.abs(np.asarray(self.energy_history) - E0)) / np.abs(E0) print(f"✅ Initial Total Energy: {E0:.6f}") print(f"✅ Max Relative Drift: {drift:.2e}")
[docs] def show_stationary_solution( self, u: Optional[np.ndarray] = None, component: str = 'abs', cmap: str = 'viridis' ) -> None: """ Display the stationary solution computed by solve_stationary_psiOp. This method visualizes the solution of a pseudo-differential equation solved in stationary mode. It supports both 1D and 2D spatial domains, with options to display different components of the solution (real, imaginary, absolute value, or phase). Parameters ---------- u : ndarray, optional Precomputed solution array. If None, calls solve_stationary_psiOp() to compute the solution. component : str, optional {'real', 'imag', 'abs', 'angle'} Component of the complex-valued solution to display: - 'real': Real part - 'imag': Imaginary part - 'abs' : Absolute value (modulus) - 'angle' : Phase (argument) cmap : str, optional Colormap used for 2D visualization (default: 'viridis'). Raises ------ ValueError If an invalid component is specified or if the spatial dimension is not supported (only 1D and 2D are implemented). Notes ----- - In 1D, the solution is displayed using a standard line plot. - In 2D, the solution is visualized as a 3D surface plot. """ def _get_component(u: np.ndarray) -> np.ndarray: if component == 'real': return np.real(u) elif component == 'imag': return np.imag(u) elif component == 'abs': return np.abs(u) elif component == 'angle': return np.angle(u) else: raise ValueError("Invalid component") if u is None: u = self.solve_stationary_psiOp() if self.dim == 1: # Plot the solution in 1D plt.figure(figsize=(8, 4)) plt.plot(self.x_grid, _get_component(u), label=f'{component} of u') plt.xlabel('x') plt.ylabel(f'{component} of u') plt.title('Stationary solution (1D)') plt.grid(True) plt.legend() plt.tight_layout() plt.show() elif self.dim == 2: fig = plt.figure(figsize=(12, 6)) ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel(f'{component.title()} of u') plt.title('Stationary solution (2D)') data0 = _get_component(u) ax.plot_surface(self.X, self.Y, data0, cmap='viridis') plt.tight_layout() plt.show() else: raise ValueError("Only 1D and 2D display are supported.")
[docs] def animate( self, component: str = 'abs', overlay: Optional[str] = 'contour', mode: str = 'surface', physical: bool = True ) -> FuncAnimation: """ Create an animated plot of the solution evolution over time. This method generates a dynamic visualization of the stored solution frames `self.frames`. It supports: - 1D line animation (unchanged), - 2D surface animation (original behavior, 'surface'), - 2D image animation using imshow (new, 'imshow') which is faster and often clearer for large grids. Parameters ---------- component : str, optional, one of {'real', 'imag', 'abs', 'angle'} Which component of the complex field to visualize: - 'real' : Re(u) - 'imag' : Im(u) - 'abs' : |u| - 'angle' : arg(u) Default is 'abs'. overlay : str or None, optional, one of {'contour', 'front', None} For 2D modes only. If None, no overlay is drawn. - 'contour' : draw contour lines on top (or beneath for 3D surface) - 'front' : detect and mark wavefronts using gradient maxima Default is 'contour'. mode : str, optional, one of {'surface', 'imshow'} 2D rendering mode. 'surface' keeps the original 3D surface plot. 'imshow' draws a 2D raster (faster, often more readable). Default is 'surface' for backward compatibility. physical : bool, default=True If True, the animation is displayed using true physical proportions of the domain. Returns ------- FuncAnimation A Matplotlib `FuncAnimation` instance (you can display it in a notebook or save it to file). Notes ----- - The method uses the same time-mapping logic as before (linear sampling of stored frames to animation frames). - For 'angle' the color scale is fixed between -π and π. - For other components, color scaling is by default dynamically adapted per frame in 'imshow' mode (this avoids extreme clipping if amplitudes vary). - Overlays are updated cleanly: previous contour/scatter artists are removed before drawing the next frame to avoid memory/visual accumulation. - Animation interval is 50 ms per frame (unchanged). """ def _get_component(u: np.ndarray) -> np.ndarray: if component == 'real': return np.real(u) elif component == 'imag': return np.imag(u) elif component == 'abs': return np.abs(u) elif component == 'angle': return np.angle(u) else: raise ValueError("Invalid component: choose 'real','imag','abs' or 'angle'") print("\n*********************") print("* Solution plotting *") print("*********************\n") # === Calculate time vector of stored frames === save_interval = max(1, self.Nt // self.n_frames) frame_times = np.arange(0, self.Lt + self.dt, save_interval * self.dt) # === Target times for animation === target_times = np.linspace(0, self.Lt, self.n_frames // 2) # Map target times to nearest frame indices frame_indices = [np.argmin(np.abs(frame_times - t)) for t in target_times] plt.ioff() # ------------------------- # 1D case (unchanged logic) # ------------------------- if self.dim == 1: fig, ax = plt.subplots() initial = _get_component(self.frames[0]) line, = ax.plot(self.X, np.real(initial) if np.iscomplexobj(initial) else initial) ax.set_ylim(np.min(initial), np.max(initial)) ax.set_xlabel('x') ax.set_ylabel(f'{component} of u') ax.set_title('Initial condition', pad=20) plt.tight_layout(rect=[0, 0, 1, 0.95]) def _update_1d(frame_number): frame = frame_indices[frame_number] ydata = _get_component(self.frames[frame]) ydata_real = np.real(ydata) if np.iscomplexobj(ydata) else ydata line.set_ydata(ydata_real) ax.set_ylim(np.min(ydata_real), np.max(ydata_real)) current_time = target_times[frame_number] eq_latex = latex(self.equation) if hasattr(self, 'equation') else '' title = f'${eq_latex}$\nSolution at t = {current_time:.2f}' if eq_latex else f'Solution at t = {current_time:.2f}' ax.set_title(title, pad=20) return (line,) ani = FuncAnimation(fig, _update_1d, frames=len(target_times), blit=True, interval=50) plt.close(fig) return ani # ------------------------- # 2D case # ------------------------- # Validate mode if mode not in ('surface', 'imshow'): raise ValueError("Invalid mode: choose 'surface' or 'imshow'") # Common data data0 = _get_component(self.frames[0]) if mode == 'surface': # original surface behavior, but ensure clean updates fig = plt.figure(figsize=(20, 12)) ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel(f'{component.title()} of u') ax.zaxis.labelpad = 0 ax.set_title('Initial condition', pad=20) plt.tight_layout(rect=[0, 0, 1, 0.95]) # Calculate physical domain lengths Lx = self.x_grid[-1] - self.x_grid[0] Ly = self.y_grid[-1] - self.y_grid[0] surf = ax.plot_surface(self.X, self.Y, data0, cmap='viridis') plt.tight_layout(rect=[0, 0, 1, 0.95]) def _update_surface(frame_number): frame = frame_indices[frame_number] current_data = _get_component(self.frames[frame]) z_offset = np.max(current_data) + 0.05 * (np.max(current_data) - np.min(current_data)) ax.clear() # This forces the X-Y plane to match your Lx and Ly (e.g., 10 and 40) # The '1' represents the Z-axis scale. if physical: ax.set_box_aspect([Lx, Ly, 1]) # -------------------------------- surf_obj = ax.plot_surface(self.X, self.Y, current_data, cmap='viridis', vmin=(-np.pi if component == 'angle' else None), vmax=(np.pi if component == 'angle' else None)) # overlays if overlay == 'contour': # place contours slightly below the surface (use offset) try: ax.contour(self.X, self.Y, current_data, levels=10, cmap='cool', offset=z_offset) except Exception: # fallback: simple contour without offset if not supported ax.contour(self.X, self.Y, current_data, levels=10, cmap='cool') elif overlay == 'front': dx = self.x_grid[1] - self.x_grid[0] dy = self.y_grid[1] - self.y_grid[0] # numpy.gradient: axis0 -> y spacing, axis1 -> x spacing du_dy, du_dx = np.gradient(current_data, dy, dx) grad_norm = np.sqrt(du_dx**2 + du_dy**2) local_max = (grad_norm == maximum_filter(grad_norm, size=5)) if np.max(grad_norm) > 0: normalized = grad_norm[local_max] / np.max(grad_norm) else: normalized = np.zeros(np.count_nonzero(local_max)) colors = cm.plasma(normalized) ax.scatter(self.X[local_max], self.Y[local_max], z_offset * np.ones_like(self.X[local_max]), color=colors, s=10, alpha=0.8) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel(f'{component.title()} of u') current_time = target_times[frame_number] eq_latex = latex(self.equation) if hasattr(self, 'equation') else '' title = f'${eq_latex}$\nSolution at t = {current_time:.2f}' if eq_latex else f'Solution at t = {current_time:.2f}' ax.set_title(title, pad=2) return (surf_obj,) ani = FuncAnimation(fig, _update_surface, frames=len(target_times), interval=50) plt.close(fig) return ani else: # mode == 'imshow' fig, ax = plt.subplots(figsize=(8, 7)) ax.set_xlabel('x') ax.set_ylabel('y') eq_latex = latex(self.equation) if hasattr(self, 'equation') else '' init_title = 'Initial condition\n$' + eq_latex + '$' if eq_latex else 'Initial condition' ax.set_title(init_title, fontsize=9) # extent uses physical coordinates so axes show real x/y values extent = [self.x_grid[0], self.x_grid[-1], self.y_grid[0], self.y_grid[-1]] if component == 'angle': vmin, vmax = -np.pi, np.pi cmap = 'twilight' else: vmin, vmax = np.min(data0), np.max(data0) cmap = 'viridis' if physical: aspect = 'equal' else: aspect = 'auto' im = ax.imshow(data0, extent=extent, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax, aspect=aspect) cbar = fig.colorbar(im, ax=ax) cbar.set_label(f"{component} of u") plt.tight_layout(rect=[0, 0, 1, 0.95]) fig.subplots_adjust(top=0.85) # containers for dynamic overlay artists (stored on function object) # update_im.contour_art and update_im.scatter_art will be created dynamically def update_im(frame_number): frame = frame_indices[frame_number] current_data = _get_component(self.frames[frame]) # update raster im.set_data(current_data) if component != 'angle': # dynamic per-frame scaling (keeps contrast when amplitude varies) cmin = np.nanmin(current_data) cmax = np.nanmax(current_data) # avoid identical vmin==vmax if cmax > cmin: im.set_clim(cmin, cmax) # remove previous contour if exists if overlay == 'contour': if hasattr(update_im, 'contour_art') and update_im.contour_art is not None: try: update_im.contour_art.remove() except (ValueError, AttributeError): pass update_im.contour_art = None # draw new contours (use meshgrid coords) try: update_im.contour_art = ax.contour(self.X, self.Y, current_data.T, levels=10, cmap='cool') except Exception: # fallback: contour with axis coordinates (x_grid, y_grid) Xc, Yc = np.meshgrid(self.x_grid, self.y_grid) update_im.contour_art = ax.contour(Xc, Yc, current_data.T, levels=10, cmap='cool') # remove previous scatter if exists if overlay == 'front': if hasattr(update_im, 'scatter_art') and update_im.scatter_art is not None: try: update_im.scatter_art.remove() except Exception: pass update_im.scatter_art = None dx = self.x_grid[1] - self.x_grid[0] dy = self.y_grid[1] - self.y_grid[0] du_dy, du_dx = np.gradient(current_data, dy, dx) grad_norm = np.sqrt(du_dx**2 + du_dy**2) local_max = (grad_norm == maximum_filter(grad_norm, size=5)) if np.max(grad_norm) > 0: normalized = grad_norm[local_max] / np.max(grad_norm) else: normalized = np.zeros(np.count_nonzero(local_max)) colors = cm.plasma(normalized) update_im.scatter_art = ax.scatter(self.X[local_max], self.Y[local_max], c=colors, s=10, alpha=0.8) current_time = target_times[frame_number] eq_latex = latex(self.equation) if hasattr(self, 'equation') else '' title = f'${eq_latex}$\nSolution at t = {current_time:.2f}' if eq_latex else f'Solution at t = {current_time:.2f}' ax.set_title(title, pad=2, fontsize=9) # return main image plus any overlay artists present so Matplotlib can redraw them artists = [im] if overlay == 'contour' and hasattr(update_im, 'contour_art') and update_im.contour_art is not None: artists.extend(update_im.contour_art.collections if hasattr(update_im.contour_art, 'collections') else update_im.contour_art.get_paths() and [update_im.contour_art]) if overlay == 'front' and hasattr(update_im, 'scatter_art') and update_im.scatter_art is not None: artists.append(update_im.scatter_art) return tuple(artists) ani = FuncAnimation(fig, update_im, frames=len(target_times), interval=50) plt.close(fig) return ani
[docs] def test( self, u_exact: Callable[..., np.ndarray], t_eval: Optional[float] = None, norm: str = 'relative', threshold: float = 1e-2, component: str = 'real' ) -> float: """ Test the solver against an exact solution. Quantitatively compares the numerical solution with a provided exact solution at a specified time using either relative or absolute error norms. Parameters ---------- u_exact : callable Exact solution function taking spatial coordinates and optionally time as arguments. t_eval : float, optional Time at which to compare solutions. For non-stationary problems, defaults to final time Lt. norm : str {'relative', 'absolute'} Type of error norm used in comparison. threshold : float Acceptable error threshold; raises an assertion if exceeded. component : str {'real', 'imag', 'abs'} Component of the solution to compare and visualize. Raises ------ ValueError If unsupported dimension is encountered or requested evaluation time exceeds simulation duration. AssertionError If computed error exceeds the given threshold. Notes ----- - For time-dependent problems, the solution is extracted from precomputed frames. - Plots are adapted to spatial dimension: line plots for 1D, image plots for 2D. - Prints information about the closest available frame and the computed error value. """ if self.is_stationary: print("Testing a stationary solution.") u_num = self.u # Compute exact solution if self.dim == 1: u_ex = u_exact(self.X) elif self.dim == 2: u_ex = u_exact(self.X, self.Y) else: raise ValueError("Unsupported dimension.") actual_t = None else: if t_eval is None: t_eval = self.Lt if t_eval < 0 or t_eval > self.Lt + 0.5 * self.dt: raise ValueError( f"t_eval = {t_eval} is outside the simulation interval " f"[0, {self.Lt}]." ) save_interval = max(1, self.Nt // self.n_frames) frame_times = np.arange(0, self.Lt + self.dt, save_interval * self.dt) frame_index = np.argmin(np.abs(frame_times - t_eval)) actual_t = frame_times[frame_index] print(f"Closest available time to t_eval={t_eval}: {actual_t}") if frame_index >= len(self.frames): raise ValueError(f"Time t = {t_eval} exceeds simulation duration.") u_num = self.frames[frame_index] # Compute exact solution at the actual time if self.dim == 1: u_ex = u_exact(self.X, actual_t) elif self.dim == 2: u_ex = u_exact(self.X, self.Y, actual_t) else: raise ValueError("Unsupported dimension.") # Select component if component == 'real': diff = np.real(u_num) - np.real(u_ex) ref = np.real(u_ex) elif component == 'imag': diff = np.imag(u_num) - np.imag(u_ex) ref = np.imag(u_ex) elif component == 'abs': diff = np.abs(u_num) - np.abs(u_ex) ref = np.abs(u_ex) else: raise ValueError("Invalid component.") # Compute error if norm == 'relative': error = np.linalg.norm(diff) / np.linalg.norm(ref) elif norm == 'absolute': error = np.linalg.norm(diff) else: raise ValueError("Unknown norm type.") label_time = f"t = {actual_t}" if actual_t is not None else "" print(f"Test error {label_time}: {error:.3e}") assert error < threshold, f"Error too large {label_time}: {error:.3e}" # Plot if self.plot: if self.dim == 1: plt.figure(figsize=(12, 6)) plt.subplot(2, 1, 1) plt.plot(self.X, np.real(u_num), label='Numerical') plt.plot(self.X, np.real(u_ex), '--', label='Exact') plt.title(f'Solution {label_time}, error = {error:.2e}') plt.legend() plt.grid() plt.subplot(2, 1, 2) plt.plot(self.X, np.abs(diff), color='red') plt.title('Absolute Error') plt.grid() plt.tight_layout() plt.show() else: extent = [-self.Lx/2, self.Lx/2, -self.Ly/2, self.Ly/2] plt.figure(figsize=(15, 5)) plt.subplot(1, 3, 1) plt.title("Numerical Solution") plt.imshow(np.abs(u_num), origin='lower', extent=extent, cmap='viridis') plt.colorbar() plt.subplot(1, 3, 2) plt.title("Exact Solution") plt.imshow(np.abs(u_ex), origin='lower', extent=extent, cmap='viridis') plt.colorbar() plt.subplot(1, 3, 3) plt.title(f"Error (Norm = {error:.2e})") plt.imshow(np.abs(diff), origin='lower', extent=extent, cmap='inferno') plt.colorbar() plt.tight_layout() plt.show() return error