Repository navigation
Add PseudospectralDiscretization (Chebyshev + Fourier collocation) - #690
ChrisRackauckas merged 4 commits into
Conversation
Adds a new discretization `PseudospectralDiscretization(dxs, time)` that replaces each spatial `Differential(x)^d` with the dense differentiation matrix of the spectral interpolant on a collocation grid, modeled on the SciMLBenchmarks SimpleHandwrittenPDE spectral implementations (Allen-Cahn and Burgers on Chebyshev grids, KdV and Kuramoto-Sivashinsky on periodic Fourier grids). Each direction takes a collocation specification: - `x => n` or `x => ChebyshevCollocation(n)`: Chebyshev-Lobatto nodes, for non-periodic directions with truncating boundary conditions. - `x => FourierCollocation(n)`: equispaced trigonometric collocation for periodic directions; requires `u(t, a) ~ u(t, b)` and skips the redundant higher-order derivative matching conditions, which hold identically for the interpolant. - `x => grid::AbstractVector`: custom nodes via Fornberg weights. The implementation reuses the existing PDEBase parser, boundary-condition machinery, DiscreteSpace, metadata and problem construction; the shared entry points (`discretize`, `DAEProblem`, `ODEFunction`, `generate_metadata`, `generate_ic_defaults`, ...) now dispatch on the `MOLDiscretization` union. Nested derivative terms such as `Dx(u^2)` or `Dx(a(u) * Dx(u))` are evaluated directly by collocation, so the FD-oriented system transformation is bypassed for this discretization. Validated against the handwritten benchmark forms: generated semi-discrete right-hand sides match the differentiation-matrix formulations to machine precision, and manufactured-solution solves converge as expected. A new `Pseudospectral` test group covers matrix correctness, all four benchmark equations, boundary-condition handling and error paths. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.21 Agent-Model: SWE-2 Max Agent-Session: tourmaline-street (local Devin CLI session; transcript at ~/.local/share/devin/cli/summaries/history_0d076bb1fecb4806.md)
f14db25 to
dfdbe72
Compare
The interior of each PDE is now one symbolic array equation over slices, with every spatial derivative a `SpectralApply` operator that holds its differentiation block and applies it along its axis. Nested derivatives evaluate their argument on the whole direction first. Boundary faces in 2D go through `array_bc_eqs`, whose derivative rule is factored into `array_boundary_derivative_expr` so a spectral operator supplies the boundary row as a matrix product instead of a sum of `n` slices. Patterns without a slice form fall back to the pointwise collocation rules. The symbolic system size no longer grows with resolution: the Kuramoto- Sivashinsky benchmark at 128 Fourier points builds and compiles in under a second instead of about seventy. Document which boundary conditions the Chebyshev and Fourier grids accept and how they are imposed, correct the description of how this relates to the SciMLBenchmarks spectral implementations, and test Neumann, Robin, time-dependent, second-order and nested-derivative conditions, custom grids, coupled systems, two spatial dimensions and stationary problems against manufactured solutions. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J Claude-Session: https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J
… in any dimension `FourierCollocation` directions apply whole-direction derivatives as `irfft((ik)^d .* rfft(u))` when an AbstractFFTs backend such as FFTW is loaded, through the new `MethodOfLinesAbstractFFTsExt` extension. The Nyquist mode is zeroed so the result equals the dense matrix `D1^d` to roundoff; boundary rows, pinned rows and dual-number evaluations keep using the dense matrix, which the operator carries. `FourierCollocation(n; fft = false)` opts out. AbstractFFTs is MIT; FFTW is a test dependency only. `apply_along` contracts a differentiation operator over any axis of an array of any rank, so the slice form now covers three and more spatial dimensions instead of falling back to pointwise equations. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J Claude-Session: https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J
| struct PseudospectralDiscretization <: AbstractEquationSystemDiscretization | ||
| dxs::Any | ||
| time::Any | ||
| kwargs::Any | ||
| end |
There was a problem hiding this comment.
Removed in 8bc50e9; it was copied from the MOLFiniteDifference page.
| This is the collocation family used by the SciMLBenchmarks | ||
| `SimpleHandwrittenPDE` spectral work-precision benchmarks | ||
| ([Allen–Cahn](https://docs.sciml.ai/SciMLBenchmarksOutput/stable/SimpleHandwrittenPDE/allen_cahn_spectral_wpd/), | ||
| [Burgers](https://docs.sciml.ai/SciMLBenchmarksOutput/stable/SimpleHandwrittenPDE/burgers_spectral_wpd/), | ||
| [KdV](https://docs.sciml.ai/SciMLBenchmarksOutput/stable/SimpleHandwrittenPDE/kdv_spectral_wpd/) and | ||
| [Kuramoto–Sivashinsky](https://docs.sciml.ai/SciMLBenchmarksOutput/stable/SimpleHandwrittenPDE/ks_spectral_wpd/)), | ||
| which also apply dense differentiation matrices in grid space. The periodic |
There was a problem hiding this comment.
No need to mention this. It's just a normal method.
| derivative is `irfft((ik)^d .* rfft(u))` when an `AbstractFFTs` backend such as | ||
| `FFTW` is loaded, and the equivalent dense trigonometric differentiation matrix | ||
| otherwise; see [FFT derivatives](@ref pseudospectral-fft). |
There was a problem hiding this comment.
Isn't chebyshev also FFTs?
There was a problem hiding this comment.
Yes. Done in 8bc50e9: with an AbstractFFTs backend loaded, Chebyshev directions now take the DCT-I via the real FFT of the even extension, apply the coefficient recurrence d times, and transform back, matching the differentiation matrix to roundoff. Intro reworded accordingly.
| benchmarks convert the `SummationByPartsOperators` Fourier operator to the same | ||
| dense matrix `FourierCollocation` builds. The non-periodic benchmarks use | ||
| rectangular collocation from `ClassicalOrthogonalPolynomials` (the equation is | ||
| imposed on `n - 2` first-kind Chebyshev points and mapped back through a | ||
| resampling mass matrix), whereas `ChebyshevCollocation` uses square | ||
| Chebyshev–Lobatto collocation with the boundary rows replaced by the boundary | ||
| conditions, as in Trefethen's *Spectral Methods in MATLAB*. Both are spectrally |
There was a problem hiding this comment.
Is this actually the fastest implementation? It should be able to be represented by an FFT as well, though with a sparse operator for fixing boundaries.
There was a problem hiding this comment.
It was not; the dense matrix product was the only path. 8bc50e9 adds the FFT path for Chebyshev directions. The derivative is computed on all nodes by the transform and the interior equation slices out the interior rows, so the boundary handling is that slice plus the boundary rows the BCs replace, no separate operator needed. Measured on Burgers, prob.f: n=257 46 us dense vs 38 us FFT; n=1025 198 vs 113; n=4097 8.3 ms vs 0.49 ms. Transform length is 2(n-1), so n = 2^k+1 is fastest. The dense matrix also moved from full-stencil Fornberg weights, which overflow to NaN past ~1000 nodes, to the Weideman-Reddy chebdif recursion.
…atrix Review follow-up. The AbstractFFTs extension now also covers `ChebyshevCollocation`: the DCT-I of each line is the real FFT of its even extension, the derivative's coefficients follow from the backward recurrence applied `d` times, and the same transform maps back to the nodes. The result equals the differentiation matrix to roundoff. The interior equation slices the interior rows out of the whole-direction derivative, which is the "sparse operator for the boundaries"; boundary rows and dual-number evaluations keep the dense matrix. Both FFT operators cache plans and work buffers per array size and apply in place. The dense Chebyshev matrix is now built with the Weideman-Reddy `chebdif` recursion instead of full-stencil Fornberg weights, which overflow to NaN beyond roughly a thousand nodes; the two agree to 1e-12 below that and `chebdif` is the more accurate one for second derivatives at several hundred nodes. Custom node vectors keep the Fornberg construction. Docs: drop the struct listing and the benchmark comparison, describe both FFT paths and the `n = 2^k + 1` transform length. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J Claude-Session: https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J
- Add a tutorial on the two-dimensional Brusselator UDE (#687) - Add PseudospectralDiscretization (Chebyshev + Fourier collocation) (#690) Agent-Harness: Claude Code Agent-Model: claude-opus-5[1m] Claude-Session: https://claude.ai/code/session_014FEzNTLFutCmTEAZ3zBg5R Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
Adds
PseudospectralDiscretization, a collocation discretization withChebyshevCollocation(n)(Chebyshev–Lobatto nodes, polynomial-interpolant differentiation matrices),FourierCollocation(n)(equispaced periodic nodes, trigonometric-interpolant matrices) and custom node vectors, inside MethodOfLines.jl with no new dependencies. It reuses theVariableMap/boundarymap/InteriorMap/DiscreteSpace/EquationStateparsing, the boundary-condition machinery,mtkcompile/DAEProblem/NonlinearProblemconstruction and thesol[u(t, x)]solution interface; the discretization-specific parts are grid construction, the differentiation matrices, and equation generation. Shared entry points were widened toMOLDiscretization = Union{MOLFiniteDifference, PseudospectralDiscretization}.What it is, precisely. Collocation in physical (grid) space: unknowns are nodal values, each
Differential(x)^dis a dense differentiation matrix, nonlinear terms are evaluated pointwise on the grid. No FFTs are used and nothing is solved in coefficient space; a Fourier direction uses the dense trigonometric differentiation matrix, which is what theSummationByPartsOperatorsoperator in the KdV/KS benchmarks becomes afterMatrix(D). The Chebyshev benchmarks use rectangular collocation with a resampling mass matrix; here it is square Lobatto collocation with boundary-row replacement (Trefethen'scheb). Both are spectrally accurate; the operators differ.Array form (second commit). The first commit generated one scalar equation per node, each a dense
n-term row, so the symbolic system wasO(n^2)and the KS benchmark at its published size (128 Fourier points) took ~70 s to build and compile. The interior is now emitted as one array equation over slices, with each derivative an opaqueSpectralApplyoperator holding its matrix block and applying it along its axis (Dsub * u/u * Dsub'), nested derivatives evaluated on the full direction first (Dx(a(u)*Dx(u))→D1 * (a.(u) .* (D1 * u))), and 2D faces going througharray_bc_eqswith a spectral method of the newarray_boundary_derivative_exprhelper (a one-block refactor of the finite-difference loop, behaviour unchanged). 3D, stationary systems and patterns without a slice form fall back to the pointwise path. TheDAEProblemfromdiscretizekeeps the array form;mtkcompilescalarizes it but the generated code evaluates each matrix product once (CSE), verified by timing.Boundary conditions. Chebyshev: the PDE is imposed at interior nodes and each boundary node's equation is replaced by the BC; a derivative in a BC is the boundary row of the differentiation matrix over all
nvalues. Dirichlet (constant/time-dependent/face-varying), Neumann, Robin, nonlinear, second-order, several conditions per end (clamped beam), and one-sided conditions (advection) all work; each condition removes one more node from the interior at that end. Boundary values are algebraic unknowns, sodiscretizereturns an index-1DAEProblemwithBrownFullBasicInit. Fourier:n + 1stored points with the last aliasing the first, pinned byu(t,a) ~ u(t,b); derivative matching conditions are checked to hold identically and skipped; a jump in one raises an error; truncating BCs are rejected. All of this is now indocs/src/pseudospectral.md.FFT derivatives and N-dimensional array form (third commit). A new
MethodOfLinesAbstractFFTsExtextension (weak dependencyAbstractFFTs, MIT;FFTWadded as a test dependency only, itsFFTW_jllis GPL and stays out of[deps]) makes everyFourierCollocationdirection apply whole-direction derivatives asirfft((ik)^d .* rfft(u))along its axis once a backend is loaded, with the Nyquist mode zeroed so the result equals the denseD1^dto roundoff. Boundary rows, pinned rows and dual-number (Jacobian) evaluations keep the dense matrix, which the operator carries;FourierCollocation(n; fft = false)opts out.apply_alongcontracts an operator over any axis of an array of any rank, so the slice form now covers 3D and above instead of falling back to pointwise; a 3D Chebyshev×Chebyshev×Fourier heat problem has 18 symbolic equations at 8³, 16³ and 24³ and matches its manufactured solution to 1e-10 away from the periodic alias corners.Does the FFT make a noticeable difference? For the residual evaluation yes at large
n, no below a few hundred points, and it does not change the compile-time story:FourierCollocation(N)prob.fcallprob.fcallD1^4roundoff)Full KS solve at N = 1024 with the default
DFBDF, 2081fcalls: 1.83 s dense vs 1.09 s FFT; the rest is the dense Jacobian and linear algebra, which the FFT does not touch. On a 128×128 periodic 2D heat problem the residual costs 1.5 ms dense vs 1.4 ms FFT, because the per-element scalarized residual (#691) dominates, anddiscretizetakes about two minutes either way for the 16,641 unknowns. 3D 24³ (13,824 unknowns): 75 sdiscretize, 1.2 ms perfcall.Extension verification:
GROUP=Pseudospectralnow runs two safetestsets, 70 + 174 tests, both passing (after the fourth commit);GROUP=QA21/21 with the extension (Aqua, ExplicitImports, JET); Runic and typos clean; docs build renders the new "FFT derivatives" section.Review follow-up (fourth commit). Chebyshev directions now go through the FFT as well: the DCT-I of each line is the real FFT of its even extension, the derivative's Chebyshev coefficients come from the backward recurrence
b[k-1] = b[k+1] + 2k a[k]applieddtimes, and the same transform maps back to the nodes; the interior equation slices the interior rows out of the whole-direction derivative (the boundary rows are the ones the boundary conditions replace). Both FFT operators cache plans and buffers and apply in place. Agreement with the dense matrices is 1e-13 to 1e-9 relative for orders 1 to 4 (tests). The transform length is2(n - 1), son = 2^k + 1is fastest.While benchmarking this I found that the dense Chebyshev matrix built from full-stencil Fornberg weights overflows to NaN beyond about a thousand nodes (
n = 1025:D1is NaN), which also breaks the FFT path's Jacobians.spectral_diff_matrixforChebyshevCollocationnow uses the Weideman–Reddychebdifrecursion: equal to Fornberg to 1e-12 forn ≤ 513(and more accurate forD2there: 8.6e-7 vs 4.9e-6 onexp(sin(3x))), finite and accurate at 1025 and 2049. Custom node vectors keep Fornberg.Burgers on Chebyshev nodes,
prob.fcall (Julia 1.10.11, FFTW):Bare operator on a vector,
n = 1024vs1025: FFT 78 µs vs 22 µs (length 2046 has a factor 31), dense 34 µs vs 79 µs. Full Burgers solve at 257 nodes: 0.15 s either way.Docs: the struct listing and the benchmark-comparison paragraph are gone; the intro says both directions use FFTs with a backend loaded.
QA on a fresh Manifest.
GROUP=QApassed on 2026-09-11 (21/21) but on a Manifest resolved on 2026-09-12 it fails two ExplicitImports "via owners" checks on pre-existing imports insrc/MethodOfLines.jl(get_eqs,get_unknowns,ProblemTypeCtx,VariableBounds, ... now reported as owned byModelingToolkitBase). Nothing in this PR touches those lines; it reproduces with the new dependency versions on master and is being handled separately.Verification
GROUP=Pseudospectral julia --project -e 'using Pkg; Pkg.test()'(Julia 1.10.11):Covers: differentiation matrices against Trefethen's
cheband exact trigonometric derivatives; equation count independent of resolution (3 equations in 1D at n = 8 and 40, 6 in 2D Chebyshev×Fourier at 8×8 and 24×20); DAE residual of the array form against handwrittenD1/D2/D3/D4matrix products for Allen–Cahn, Burgers (conservative and convective), KdV and KS to 1e-9; manufactured solutions to ≤1e-6 (measured 1e-10–1e-11) for Dirichlet, custom nodes, Neumann, Robin, time-dependent Dirichlet, second-order BCs, nestedDx((1+x^2) Dx u), a coupled two-variable system, Fourier (even and oddn), 2D Chebyshev×Chebyshev and 2D Chebyshev×Fourier with a Neumann face, and a stationaryNonlinearProblem; error cases.Shared-code groups run locally after the
array_bc_eqsrefactor, all passing with only the pre-existing@test_brokenentries:2D_Diffusion(2/2),DAE(22/22),Higher_Order(1 + 2 broken),Mixed_Derivatives(2 + 3 broken),Nonlinear_Diffusion(10 + 2 broken),Integrals(2 + 2 broken),Diffusion(269/269),Components,Discretization,Brusselator,QA— see the log tails below.GROUP=2D_Diffusion: passed —Test Summary: | Pass Total Time / 2D_Diffusion | 2 2 4m04.3sGROUP=DAE: passed —Test Summary: | Pass Total Time / DAE | 22 22 2m43.7sGROUP=Higher_Order: passed —Test Summary: | Pass Broken Total Time / Higher_Order | 1 2 3 4m28.5sGROUP=Mixed_Derivatives: passed —Test Summary: | Pass Broken Total Time / Mixed_Derivatives | 2 3 5 7m36.7sGROUP=Nonlinear_Diffusion: passed —Test Summary: | Pass Broken Total Time / Nonlinear_Diffusion | 10 2 12 4m04.6sGROUP=Integrals: passed —Test Summary: | Pass Broken Total Time / Integrals | 2 2 4 2m38.4sGROUP=Diffusion: passed —Test Summary: | Pass Total Time / Diffusion | 269 269 8m27.5sGROUP=Components: passed —Test Summary: | Pass Total Time / Discrete Callbacks | 1 1 43.6sGROUP=Discretization: passed —Test Summary: | Pass Total Time / Problem construction | 54 54 1m13.9sGROUP=Brusselator: passed —Test Summary: | Pass Total Time / Brusselator | 1154 1154 27m40.2sGROUP=QA: passed —Test Summary: | Pass Total Time / QA | 21 21 13m45.0sGROUP=Sol_Interface: passed —Test Summary: | Pass Total Time / Sol_Interface | 18 18 5m23.2sGROUP=MOL_Interface1: passed —Test Summary: | Total Time / MOL_Interface1 | 0 12m49.2sGROUP=MOL_Interface2: passed —Test Summary: | Pass Broken Total Time / MOL_Interface2 | 8 5 13 7m36.9sGROUP=Stationary: passed —Test Summary: | Pass Total Time / Stationary | 8 8 4m00.6sGROUP=Complex: passed —Test Summary: | Pass Total Time / Complex | 102 102 2m45.3sGROUP=Convection: passed —Test Summary: | Pass Broken Total Time / Convection | 8 1 9 4m16.1sGROUP=Convection_WENO: passed —Test Summary: | Pass Total Time / WENO Non-Uniform Interface/Periodic | 31 31 4m11.8sGROUP=Convection_NU: passed —Test Summary: | Pass Total Time / Linear Convection, Upwind Non-Uniform Interfaces | 109 109 3m10.7sGROUP=Diffusion_NU: passed —Test Summary: | Pass Total Time / Diffusion_NU | 150 150 6m10.4sGROUP=Nonlinear_Diffusion_NU: passed —Test Summary: | Pass Broken Total Time / Nonlinear_Diffusion_NU | 13 2 15 3m56.2sGROUP=Nonlinlap_ADV: passed —Test Summary: | Broken Total Time / Nonlinlap_ADV | 1 1 2m57.3sGROUP=Burgers: passed —Test Summary: | Pass Total Time / Burgers | 128 128 3m28.8sGROUP=Wave_Eq_Staggered: passed —Test Summary: | Pass Broken Total Time / Wave_Eq_Staggered | 1 5 6 3m38.3sRunic (
--check) andtyposclean on every changed file. Docs build:julia --project=docs docs/make.jlran toRenderDocumentwith no errors and the new page and theSpectralApplydocstring rendered; the only failure in a full run waslinkcheckreturning HTTP 429 (GitHub rate limiting) on two pre-existing links in other pages, so the reported build usedlinkcheck = false.Compile scaling, KS with
FourierCollocation(N),discretize+ firstprob.fcall, Julia 1.10.11:MOLFiniteDifferenceorder 4prob.fruntime at N = 1024 is 226 µs, consistent with one dense matrix product per derivative per call. Neither path is resolution-independent at the compiled-code level: MTK's DAE codegen scalarizes the array residual, which is a pre-existing property of the finite-difference array path too (measured 15.8 sdiscretize+ 25.5 s first call at 4097 FD points). Filed as #691.Not verified / known gaps
MOLFiniteDifference.Integralterms and multi-domain interface BCs raise errors.julia pre, downstream) not run locally.Things to push back on
apply_alongloopsmul!over the trailing axes for a middle axis in ≥3D; a tensor library would be faster.Dictinside the operator, which is not thread-safe if the same problem is evaluated concurrently.🤖 Generated with Claude Code (model: claude-fable-5-1)
https://claude.ai/code/session_01RuwNgkber23fDw3ijCb21J
The first commit was produced by a different agent session (Devin CLI 3000.10.21, model SWE-2 Max, local session
tourmaline-street); the second commit and this description come from the Claude Code session linked above.