Skip to content

Add ArrayDiscretization: emit interior PDE equations as slice-form array equations - #604

Merged
ChrisRackauckas merged 12 commits into
SciML:masterfrom
ChrisRackauckas-Claude:array-equations-428
Aug 7, 2026
Merged

ChrisRackauckas merged 12 commits into
SciML:masterfrom
ChrisRackauckas-Claude:array-equations-428

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Note

Draft — please ignore until reviewed by @ChrisRackauckas.
Depends on SciML/PDEBase.jl#97 (needs PDEBase 0.1.30 released before CI can pass).

Closes #428.

Summary

Adds an ArrayDiscretization discretization strategy that represents the interior of each PDE as a single unscalarized symbolic array equation over slices of the underlying array variables, instead of one scalar equation per grid point. For the 1D heat equation at second order, the entire discretized system is now 3 equations:

broadcast(+, broadcast(*, -1, broadcast(+, broadcast(*, 400.0, (u(t))[1:19]),
    broadcast(*, -800.0, (u(t))[2:20]), broadcast(*, 400.0, (u(t))[3:21]))),
    Differential(t)((u(t))[2:20])) ~ zeros(19)
(u(t))[1] ~ 0.0
(u(t))[21] ~ 0.0

i.e. the D(u[2:end-1]) ~ u[1:end-2] .- 2u[2:end-1] .+ u[3:end] form sketched in #428. The number of symbolic equations is independent of grid resolution, and the array structure is what array-aware compilers need to generate looped code. Since MOL's discrete variables were already elements of array symbolics, unknowns, ICs, and the solution interface are unchanged.

Compile-time payoff

mtkcompile scalarizes array equations, so the ODEProblem path is numerically and
performance-wise unchanged today. But feeding the discretized equations straight to
Symbolics.build_function — i.e. any codegen path that does not scalarize — shows what
the representation buys, on the 1D heat equation:

grid pts scalar eqs array eqs scalar expr nodes array expr nodes codegen scalar → array first-call compile scalar → array speedup
25 23 1 738 49 0.48 ms → 0.09 ms 0.057 s → 0.035 s 1.6×
100 98 1 3 063 49 1.85 ms → 0.09 ms 0.315 s → 0.033 s 9.7×
400 398 1 12 363 49 6.73 ms → 0.09 ms 1.726 s → 0.033 s 52.6×
800 798 1 24 763 49 14.72 ms → 0.10 ms 4.392 s → 0.034 s 128.8×

Expression size and compile time are constant in grid resolution for the array form and
linear for the scalarized form. The two generated functions agree to ≤3e-12 relative,
so this is not a cheaper computation — it is the same computation expressed once.

The generated code shows the mechanism directly. Array form, one broadcast over slices:

(broadcast)(+, (broadcast)(*, -1,
  (broadcast)(+, (broadcast)(*, 576.0, (getindex)(u, 1:23)),
                 (broadcast)(*, -1152.0, (getindex)(u, 2:24)),
                 (broadcast)(*, 576.0, (getindex)(u, 3:25)))),
  (getindex)(du, 2:24))

versus the scalarized form, which unrolls every grid point:

(SymbolicUtils.Code.create_array)(Array, nothing, Val{1}(), Val{(23,)}(),
  (+)((+)((+)((getindex)(du, 2), (*)(-576.0, (getindex)(u, 1))), ...
  (+)((+)((+)((getindex)(du, 3), (*)(-576.0, (getindex)(u, 2))), ...
  ... 23 more ...

So the payoff is available now to consumers that keep the array form, and mtkcompile is
what currently erases it.

Scaling with grid resolution and dimension

Interior, boundary faces, and the corner/edge region are all emitted in slice form, so
the discretized system has the same number of equations at any grid resolution — 3^N,
one per combination of {below the interior, inside it, above it} along each axis.
Discretization time for the heat equation:

grid pts scalar eqs array eqs scalar t array t speedup
1D 400 400 400 3 47.9 s 0.23 s 201×
2D 30×30 900 900 9 7.52 s 0.14 s 52×
3D 11×11×11 1331 1331 27 7.78 s 0.13 s 60×

Array equation counts are constant across every resolution tested (1D: 50→400 pts,
2D: 10²→30², 3D: 5³→11³), and the interior expression size is likewise constant, growing
only with dimension (34 / 67 / 106 nodes) as each axis adds one stencil.

The three regions collapse for the same reason. The interior stencil is translation
invariant. On a boundary face the index along that boundary's own direction is fixed, so
every point on the face selects identical stencil weights and tap offsets — the same
invariance one dimension down. The corner/edge region is a union of boxes once its band
structure is recovered rather than computed as a setdiff over indices.

Numerics are unchanged throughout: solutions match ScalarizedDiscretization bitwise in
these cases, because each path reuses the scalar path's own weight computation.

Benchmark source (self-contained, reproduces the table above)
# Self-contained benchmark: how do the scalarized and array discretizations scale with
# grid resolution, in 1D / 2D / 3D?
#
# Measures, per strategy: discretization wall time, equation counts, and symbolic
# expression size split into the *interior* (what the array form collapses) and the
# *boundary* (which stays pointwise under both strategies).
using MethodOfLines, ModelingToolkit, DomainSets, Symbolics, SymbolicUtils
using ModelingToolkit: get_eqs

treesize(x) = let u = Symbolics.unwrap(x)
    SymbolicUtils.iscall(u) ? 1 + sum(treesize, SymbolicUtils.arguments(u); init = 0) : 1
end
isarreq(eq) = any((eq.lhs, eq.rhs)) do side
    u = Symbolics.unwrap(side)
    !(u isa AbstractArray) && SymbolicUtils.symtype(u) <: AbstractArray
end
# interior equations are the ones carrying the time derivative
isinterior(eq) = occursin("Differential(t", string(eq))

"1D/2D/3D heat equation on an n-point-per-side grid."
function heat_system(dim, n)
    @parameters t
    if dim == 1
        @parameters x
        @variables u(..)
        Dt = Differential(t)
        eq = Dt(u(t, x)) ~ (Differential(x)^2)(u(t, x))
        bcs = [u(0, x) ~ sinpi(x), u(t, 0) ~ 0.0, u(t, 1) ~ 0.0]
        dom = [t ∈ Interval(0.0, 0.1), x ∈ Interval(0.0, 1.0)]
        @named ps = PDESystem(eq, bcs, dom, [t, x], [u(t, x)])
        return ps, [x => 1 / (n - 1)]
    elseif dim == 2
        @parameters x y
        @variables u(..)
        Dt = Differential(t)
        eq = Dt(u(t, x, y)) ~ (Differential(x)^2)(u(t, x, y)) + (Differential(y)^2)(u(t, x, y))
        bcs = [
            u(0, x, y) ~ sinpi(x) * sinpi(y),
            u(t, 0, y) ~ 0.0, u(t, 1, y) ~ 0.0,
            u(t, x, 0) ~ 0.0, u(t, x, 1) ~ 0.0,
        ]
        dom = [
            t ∈ Interval(0.0, 0.1), x ∈ Interval(0.0, 1.0), y ∈ Interval(0.0, 1.0),
        ]
        @named ps = PDESystem(eq, bcs, dom, [t, x, y], [u(t, x, y)])
        return ps, [x => 1 / (n - 1), y => 1 / (n - 1)]
    else
        @parameters x y z
        @variables u(..)
        Dt = Differential(t)
        eq = Dt(u(t, x, y, z)) ~ (Differential(x)^2)(u(t, x, y, z)) +
            (Differential(y)^2)(u(t, x, y, z)) + (Differential(z)^2)(u(t, x, y, z))
        bcs = [
            u(0, x, y, z) ~ sinpi(x) * sinpi(y) * sinpi(z),
            u(t, 0, y, z) ~ 0.0, u(t, 1, y, z) ~ 0.0,
            u(t, x, 0, z) ~ 0.0, u(t, x, 1, z) ~ 0.0,
            u(t, x, y, 0) ~ 0.0, u(t, x, y, 1) ~ 0.0,
        ]
        dom = [
            t ∈ Interval(0.0, 0.1), x ∈ Interval(0.0, 1.0),
            y ∈ Interval(0.0, 1.0), z ∈ Interval(0.0, 1.0),
        ]
        @named ps = PDESystem(eq, bcs, dom, [t, x, y, z], [u(t, x, y, z)])
        return ps, [x => 1 / (n - 1), y => 1 / (n - 1), z => 1 / (n - 1)]
    end
end


function run_case(dim, n, strat)
    pdesys, dxs = heat_system(dim, n)
    @parameters t
    disc = MOLFiniteDifference(dxs, t; discretization_strategy = strat)
    t_disc = @elapsed (sys, _) = symbolic_discretize(pdesys, disc)
    eqs = get_eqs(sys)
    int = filter(isinterior, eqs)
    bnd = filter(!isinterior, eqs)
    return (;
        t_disc,
        neqs = length(eqs),
        nint = length(int),
        nbnd = length(bnd),
        narr = count(isarreq, eqs),
        int_nodes = sum(eq -> treesize(eq.lhs) + treesize(eq.rhs), int; init = 0),
        bnd_nodes = sum(eq -> treesize(eq.lhs) + treesize(eq.rhs), bnd; init = 0),
    )
end

const SIZES = Dict(1 => [50, 100, 200, 400], 2 => [10, 15, 20, 30], 3 => [5, 7, 9, 11])

# warm up: the first discretization in a session pays JIT that dwarfs the measurement
for st in [ScalarizedDiscretization(), ArrayDiscretization()], d in [1, 2, 3]
    run_case(d, 5, st)
end

for dim in [1, 2, 3]
    println("\n===== ", dim, "D heat equation =====")
    println(
        rpad("n/side", 8), rpad("pts", 8), rpad("strategy", 10),
        rpad("t_disc(s)", 11), rpad("eqs", 7), rpad("int_eqs", 9), rpad("bnd_eqs", 9),
        rpad("int_nodes", 11), rpad("bnd_nodes", 11)
    )
    for n in SIZES[dim]
        for (nm, st) in [
                ("scalar", ScalarizedDiscretization()), ("array", ArrayDiscretization()),
            ]
            r = try
                run_case(dim, n, st)
            catch e
                println(rpad(n, 8), rpad(n^dim, 8), rpad(nm, 10), "FAILED: ",
                    first(split(sprint(showerror, e), '\n'))[1:min(end, 60)])
                continue
            end
            println(
                rpad(n, 8), rpad(n^dim, 8), rpad(nm, 10),
                rpad(round(r.t_disc, digits = 3), 11), rpad(r.neqs, 7),
                rpad(r.nint, 9), rpad(r.nbnd, 9),
                rpad(r.int_nodes, 11), rpad(r.bnd_nodes, 11)
            )
            flush(stdout)
        end
    end
end
println("\nDONE")

Usage:

MOLFiniteDifference([x => dx], t; discretization_strategy = ArrayDiscretization())

Design

  • Slice rules: centered even-order derivatives and upwind odd-order derivatives (including coefficient-carrying winding terms) are built as broadcasted weighted sums of shifted slices. Nonuniform grids use per-point weight vectors reshaped to broadcast along the right dimension. Winding reproduces the scalar path's ifelse(coef > 0, coef*pos, coef*neg) exactly whenever the coefficient does not vary over the grid (a literal, a parameter, or any expression of time alone), since the wind direction is then a single scalar condition per slice. Grid-varying coefficients need a per-point condition, which ifelse cannot express (broadcasting it over a symbolic array condition fails: the elementwise comparison carries symtype Any, not Bool), so those use max(coef,0)*pos + min(coef,0)*neg — equal on finite values, differing only when the unselected stencil is Inf/NaN.
  • Core/frame split: the array equation covers the "core" region where the translation-invariant interior stencil applies; interior points near boundaries whose stencils differ (e.g. approx_order = 4) get pointwise scalar equations, mirroring the scalar path's stencil selection exactly.
  • Whole-equation fallback: patterns with no slice representation fall back to the existing pointwise discretization for that equation, producing numerics identical to ScalarizedDiscretization: WENO/functional advection, nonlinear and spherical Laplacians, integrals, mixed derivatives, interface/periodic BCs, callbacks, boundary values inside interior equations, staggered grids, and mixed-dimension variable systems.
  • Boundary/extrapolation/corner equations reuse the scalar machinery untouched.

Tests

New Array_Discretization test group (wired into test_groups.toml/runtests.jl): 1D/2D diffusion, Neumann/Robin BCs, constant and u-dependent advection (winding), space/time-dependent coefficients, 4th-order (frame points), nonuniform grid, coupled systems, stationary NonlinearProblem, and fallback cases (periodic, nonlinear Laplacian, WENO). Every case asserts agreement with ScalarizedDiscretization and, where applicable, that the interior really is one array equation.

Ran locally (Julia 1.12.4, dev'd PDEBase#97): Array_Discretization 41/41 pass — solutions match the scalar path to machine precision (bitwise-identical in most cases). Regression groups run locally: Stationary + Burgers 44/44 pass, Diffusion 288/289 (the single failure, Test 03 order-8 Neumann conservation atol, and a separate WENO single-BC initialization error were confirmed to reproduce on clean master independently of this PR — filed as #605 and #606, both traced to the #594 / PDEBase 0.1.29 initialization wiring.

CI status (rebased onto master 2026-07-22): the branch now sits on current master, inheriting #601's ModelingToolkit floor bump 11.26.8 → 11.31.2 and its Diffusion conservation-test stabilization. Version bumped to 0.11.19 (0.11.18 is already released). This clears two of the three previously-red checks:

Every functional test group, including the new Array_Discretization group, passes across Julia 1/lts/pre.).

Notes

  • The pre-existing ArrayDiscretization stub struct and the generate_interior tuple method for it were replaced; generate_interior is now a single method since the array path derives slice bounds from the same CartesianIndices interior the BC machinery uses.
  • generate_ic_defaults dispatch was widened from ScalarizedDiscretization to all strategies (same body).
  • Version bumped to 0.11.18 with PDEBase = "0.1.30".

🤖 Generated with Claude Code

https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9

ChrisRackauckas and others added 5 commits July 22, 2026 04:30
…tions

Implements the array-equation representation from SciML#428: the interior of each
PDE is discretized as a single symbolic array equation over slices of the
underlying array variables, with pointwise scalar fallback for unsupported
patterns and for near-boundary frame points.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
…rray equations

- Probe special-scheme rules with subsmatch against the equation instead of
  isempty (mixed/euler-integration rules are generated unconditionally, and
  boundary machinery always emits rules keyed on the canonical depvar)
- Detect boundary values in interior equations as depvar terms with a number
  argument
- Emit array equations as lhs ~ zeros(size) since ~ cannot equate an array
  with scalar zero
- Use unwrap_const for zero literals and symtype for array-valuedness
- Guard arrayify against unhandled operators (integrals)
- Bump version to 0.11.18, require PDEBase 0.1.30

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
… stationary test

- arrayify guarded on `Symbolics.Operator`, which is non-public in both Symbolics and
  SymbolicUtils (flagged by ExplicitImports QA) and, since `Integral <: Operator` is
  false, never actually caught the integrals its comment claimed. Guard on
  `!(op isa Function)` instead: public-API only, and correct for Integral and symbolic
  callables alike.
- The stationary test asserted `retcode == Success`. `mtkcompile` tears that linear
  system down to a single unknown, for which the solver's progress-based stall criterion
  can trip while the solution is fully converged — locally the *scalar* path reports
  Stalled under TrustRegion with a solution agreeing to 1.1e-14. Pin NewtonRaphson for
  determinism and assert the solution against the scalar path and the analytic solution,
  which is strictly stronger than the retcode check.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
ChrisRackauckas and others added 7 commits July 22, 2026 05:58
The tests reference SciMLBase.ReturnCode.Success but relied on a transitively
loaded package re-exporting the SciMLBase binding. That holds at current
dependency versions but not at the downgrade-CI floors, where the name is
undefined. Import SciMLBase directly, as the other test files do.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
…ar path handles

An A/B run of the full test suite with ArrayDiscretization as the default (identical
package versions, differing only in the default strategy) showed MOL_Interface2 failing
under the array path but passing under the scalar path.

Array-valued dependent variables (`@variables u(..)[1:n]`) discretize to a nested
getindex, so array_variable extracted a component rather than the grid-shaped array and
slicing it threw. That error was not an ArrayDiscretizationFallback, so it escaped the
catch and failed discretize outright instead of degrading to the pointwise path.

- array_variable now checks the extracted parent is a grid-shaped array of the expected
  rank, falling back when it is not
- any failure while building the array form now degrades to the pointwise path
  (rethrowing InterruptException); errors in the equation itself still surface from the
  scalar path, which raises them directly
- regression test covering array-valued dependent variables

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
The scalar path emits ifelse(coef > 0, coef*pos, coef*neg). The array path used
max(coef,0)*pos + min(coef,0)*neg because ifelse cannot broadcast over a symbolic array
condition. The two agree on finite values but differ when the unselected stencil is
Inf/NaN: the surrogate multiplies it by zero and yields NaN, where ifelse returns the
finite branch. That is reachable when a downwind stencil overflows during a Newton
iterate while the upwind branch stays finite.

When the coefficient does not vary over the grid -- a literal, a parameter, or any
expression of time alone -- the wind direction is a single scalar condition for the whole
slice, and ifelse broadcasts fine. Use it there, reproducing the scalar path exactly.
Grid-varying coefficients still need a per-point condition and keep the surrogate.

Verified against the scalar path: literal 4.9e-15, parametric 0.0, time-dependent 0.0,
grid-varying 0.0, solution-dependent 4.0e-15. Tests assert the emitted form per class.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
This strategy is opt-in, so existing code must keep getting the scalarized
discretization; nothing asserted that until now.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
…back

ArrayDiscretization silently discretizes pointwise when an equation contains a pattern
with no slice representation. That is correct but easy to miss, so a user can opt in and
not realize they got the scalar path. StrictArrayDiscretization raises
ArrayDiscretizationError instead, naming the equation and the reason.

The two strategies produce identical discretizations and differ only in that error
handling, so the machinery dispatches on a Union alias rather than duplicating methods.

Strict mode covers whole-equation fallback only. Boundary, corner and extrapolation
equations, and interior points whose stencils differ near a boundary, are pointwise under
either strategy because they are irregular by construction; erroring on those would make
the mode unusable at approx_order = 4 on even the plainest equation.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
…n O(1)

The interior collapsed to one equation, but boundary conditions stayed pointwise and
scaled with the surface, so they dominated in higher dimensions: at an 11-point 3D grid,
602 of 603 equations were boundary equations.

Boundaries on a face admit the same treatment one dimension down. The index along the
boundary's own direction is fixed across the face, so every point on it selects the same
stencil weights and tap offsets. Taking the weights the scalar path computes at a
representative face point and expressing its taps as shifted slices therefore reproduces
that path exactly, which is why the solutions are bitwise identical.

  1D:  3 ->   3 equations (unchanged; a 1D face is a point, nothing to collapse)
  2D: 117 ->  9 equations, constant in resolution (was O(n)),  10.6x -> 92x faster
  3D: 603 -> 123 equations (was O(n^2), now O(n)),              4.5x -> 58x faster

3D is not yet O(1): a cube's 12 edges are emitted by the corner-equation path as a set
difference rather than as faces, so they remain pointwise (12n - 10). Each edge is a
contiguous line and could be sliced the same way.

Also distinguishes benign fallbacks from unrepresentable ones. Declining to build an
array form because nothing would be collapsed (a single-point 1D boundary) is a
deliberate choice, not an unsupported pattern, so StrictArrayDiscretization must tolerate
it as it already tolerates frame points.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
… every dimension

Once the faces were sliced, the 3D edges were all that kept the boundary growing with
resolution, at 12n - 10 equations. They stayed pointwise only because
generate_corner_eqs! builds that region with setdiff, which returns a bag of indices and
discards the structure.

The region has structure: along each dimension a point lies in the band below the
interior, the interior band, or the band above, and this region is exactly the
combinations with at least two non-interior bands. Enumerating those recovers the boxes
and gives 3^N - 2N - 1 of them, independent of resolution: none in 1D, the 4 corners in
2D, the 12 edges and 8 corners in 3D.

Total equations are now 3^N at any grid size:

  1D:   3 equations (was 3)
  2D:   9 equations (was 9)
  3D:  27 equations (was 12n - 10, i.e. 123 at n = 11)

Discretization time is flat in resolution, against 47.9 s / 7.5 s / 7.8 s for the
scalarized path at the largest 1D / 2D / 3D grids measured.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S1dxUEPGysx27SSSpxtiQ9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants