solver
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
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
- class solver.PDESolver(equation: Equality, time_scheme: str = 'default', dealiasing_ratio: float | None = None, compute_energy: bool = True)[source]
Bases:
objectA 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
- animate(component: str = 'abs', overlay: str | None = 'contour', mode: str = 'surface', physical: bool = True) FuncAnimation[source]
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:
A Matplotlib FuncAnimation instance (you can display it in a notebook or save it to file).
- Return type:
FuncAnimation
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).
- plot_energy(log: bool = False) None[source]
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.
- setup(Lx: float, Ly: float | None = None, Nx: int | None = None, Ny: int | None = None, Lt: float = 1.0, Nt: int = 100, boundary_condition: str = 'periodic', boundary_tol: float = 1e-08, periodic_edge_tol=None, initial_condition: Callable[[...], ndarray] | None = None, initial_velocity: Callable[[...], ndarray] | None = 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[source]
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_1DSets up internal variables for one-dimensional problems.
setup_2DSets up internal variables for two-dimensional problems.
initialize_conditionsApplies initial data and enforces compatibility.
check_cfl_conditionVerifies time step against stability constraints.
plot_symbolVisualizes the linear operator’s symbol in frequency space.
analyze_wave_propagationAnalyzes group velocity.
interactive_symbol_analysisInteractive tools for ψOp-based equations.
_build_sponge_1dBuilds the 1D sponge damping profile γ(x).
_build_sponge_2dBuilds the 2D sponge damping profile γ(x, y).
_plot_sponge_profileDisplays the sponge profile for verification.
- show_stationary_solution(u: ndarray | None = None, component: str = 'abs', cmap: str = 'viridis') None[source]
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.
- solve() List[ndarray][source]
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:
A list of solution arrays at each saved time frame.
- Return type:
list of np.ndarray
Notes
Updates self.frames to store solution snapshots.
Updates self.energy_history to record total energy if enabled.
Algorithm Overview
- For each time step:
Evaluate source contributions (if any).
- 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’.
Enforce boundary conditions.
Save solution snapshot periodically.
Record energy (for second-order systems).
- solve_stationary_psiOp(order: int = 3) ndarray[source]
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:
The computed solution u(x) in 1D or u(x, y) in 2D as a NumPy array over the spatial grid.
- Return type:
ndarray
- 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_asymptoticConstructs the asymptotic inverse of the pseudo-differential operator.
kohn_nirenbergNumerical implementation of general pseudo-differential operators.
is_elliptic_numericallyVerifies numerical ellipticity of the symbol.
- test(u_exact: Callable[[...], ndarray], t_eval: float | None = None, norm: str = 'relative', threshold: float = 0.01, component: str = 'real') float[source]
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.