Skip to content

Commit 62f07c3

Browse files
Support vector-valued functions in ArrayDiscretization (#675)
f(u, θ) and (f(u, θ))[i], including NN(u, θ)[1], now map over the field slice with θ kept whole instead of falling back to pointwise. Array literals of a field such as NN([u], θ) still fall back.
1 parent b1d818f commit 62f07c3

2 files changed

Lines changed: 187 additions & 7 deletions

File tree

‎src/discretization/discretize_equations.jl‎

Lines changed: 68 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@
5757
# permuted and reshaped with singleton dimensions, matching `Idx`. A whole-domain
5858
# integrand with extra axes is a reduction (`array_integral_rules`), not a slice.
5959
#
60+
# Calls `f(u, θ)` map over the field slice without broadcasting `θ`.
61+
# `(f(u, θ))[i]` selects each point's output.
62+
#
6063
# Unsupported patterns fall back to pointwise equations: callbacks,
6164
# a higher-dimensional field whose extra axes are free (not a boundary
6265
# value and not an integral rank drop), derivatives of time-literals,
@@ -2805,6 +2808,49 @@ end
28052808
# symbolic arrays and scalars of either kind.
28062809
is_array_valued(x) = SymbolicUtils.symtype(safe_unwrap(x)) <: AbstractArray
28072810

2811+
# Parameter arrays are not grid slices and are excluded from grid broadcasts.
2812+
is_symbolic_parameter(x) = ModelingToolkitBase.isparameter(safe_unwrap(x))
2813+
is_array_parameter(x) = is_array_valued(x) && is_symbolic_parameter(x)
2814+
2815+
function is_field_parameter_call(args)
2816+
return length(args) == 2 && is_array_valued(args[1]) &&
2817+
!is_array_parameter(args[1]) && is_array_parameter(args[2])
2818+
end
2819+
2820+
array_map_callable(op, U::AbstractArray, θ) = map(ui -> op(ui, θ), U)
2821+
Symbolics.@register_array_symbolic array_map_callable(
2822+
op::Any, U::AbstractArray, θ::AbstractArray
2823+
) begin
2824+
size = size(U)
2825+
eltype = Real
2826+
end
2827+
2828+
array_map_callable_getindex(op, idx, U::AbstractArray, θ) =
2829+
map(ui -> getindex(op(ui, θ), idx), U)
2830+
Symbolics.@register_array_symbolic array_map_callable_getindex(
2831+
op::Any, idx, U::AbstractArray, θ::AbstractArray
2832+
) begin
2833+
size = size(U)
2834+
eltype = Real
2835+
end
2836+
2837+
function array_broadcast_call(op, newargs)
2838+
is_field_parameter_call(newargs) &&
2839+
return array_map_callable(op, newargs[1], newargs[2])
2840+
if any(is_array_parameter, newargs)
2841+
if op === getindex && length(newargs) == 2 &&
2842+
is_array_parameter(newargs[1]) && !is_array_valued(newargs[2])
2843+
return getindex(newargs[1], newargs[2])
2844+
end
2845+
throw(ArrayFormFallback("unhandled vector parameter in $op"))
2846+
end
2847+
any(is_array_valued, newargs) || return op(newargs...)
2848+
# `[u]` has no slice form; broadcasting the literal would wrap each point.
2849+
op isa Function && parentmodule(op) === SymbolicUtils && nameof(op) === :array_literal &&
2850+
throw(ArrayFormFallback("unhandled array literal of a field"))
2851+
return broadcast(op, newargs...)
2852+
end
2853+
28082854
function array_shape_donor(rules)
28092855
for r in rules
28102856
is_array_valued(r.second) && return r.second
@@ -2854,6 +2900,8 @@ matches a rule in `ctx.rules` (first match wins) and broadcasting any operation
28542900
receives an array-valued argument. Time differentials are applied directly to their
28552901
(array-valued) arguments; any spatial differential that survives the rules means the
28562902
expression contains a scheme this path does not support, so fall back.
2903+
2904+
Calls `f(u, θ)` map over the field slice. Indexed calls select each point's output.
28572905
"""
28582906
function arrayify(expr, ctx)
28592907
expr = safe_unwrap(expr)
@@ -2872,16 +2920,29 @@ function arrayify(expr, ctx)
28722920
throw(ArrayFormFallback("unhandled spatial derivative in $expr"))
28732921
arg = arrayify(only(arguments(expr)), ctx)
28742922
return op(arg)
2875-
elseif !(op isa Function)
2923+
end
2924+
# Index each point's callable output, not the mapped grid.
2925+
if op === getindex
2926+
args = arguments(expr)
2927+
if length(args) == 2
2928+
inner = safe_unwrap(args[1])
2929+
if iscall(inner)
2930+
iop = operation(inner)
2931+
if iop isa Function || is_symbolic_parameter(iop)
2932+
iargs = [arrayify(a, ctx) for a in arguments(inner)]
2933+
idx = arrayify(args[2], ctx)
2934+
is_field_parameter_call(iargs) ||
2935+
throw(ArrayFormFallback("unhandled callable getindex in $expr"))
2936+
return array_map_callable_getindex(iop, idx, iargs[1], iargs[2])
2937+
end
2938+
end
2939+
end
2940+
end
2941+
if !(op isa Function) && !is_symbolic_parameter(op)
28762942
# Symbolic operators (`Integral`, ...) cannot be broadcast over slices.
28772943
throw(ArrayFormFallback("unhandled operation $op in $expr"))
28782944
end
2879-
newargs = [arrayify(a, ctx) for a in arguments(expr)]
2880-
if any(is_array_valued, newargs)
2881-
return broadcast(op, newargs...)
2882-
else
2883-
return op(newargs...)
2884-
end
2945+
return array_broadcast_call(op, [arrayify(a, ctx) for a in arguments(expr)])
28852946
end
28862947

28872948
####

‎test/Discretization/equation_discretization.jl‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,125 @@ end
111111
@test maximum(abs.(sol_arr[u(t, x)] .- exact)) < 1.0e-2
112112
end
113113

114+
# Parameterized calls keep `θ` whole.
115+
vecfn_scalar(u, θ) = θ[1] * u
116+
@register_symbolic vecfn_scalar(u, θ::AbstractVector)
117+
118+
vecfn_array(u, θ) = [θ[1] * u]
119+
@register_array_symbolic vecfn_array(u::Real, θ::AbstractVector) begin
120+
size = (1,)
121+
eltype = Real
122+
end
123+
struct VectorFunctionWrapper end
124+
(::VectorFunctionWrapper)(u::Number, θ::AbstractVector) = [θ[1] * u]
125+
(::VectorFunctionWrapper)(u::AbstractVector, θ::AbstractVector) = [θ[1] * u[1]]
126+
const vecfn_wrapper = VectorFunctionWrapper()
127+
@parameters (vecfn_parameter::typeof(vecfn_wrapper))(..)[1:1] =
128+
vecfn_wrapper [tunable = false]
129+
130+
vecfn_rev(θ, u) = θ[1] * u
131+
@register_symbolic vecfn_rev(θ::AbstractVector, u)
132+
133+
function test_parameterized_heat(source; parameters = Any[], map_name = nothing)
134+
@parameters t x
135+
@parameters θ[1:2] = [1.0, 0.0]
136+
@variables u(..)
137+
Dt = Differential(t)
138+
Dxx = Differential(x)^2
139+
140+
eq = Dt(u(t, x)) ~ Dxx(u(t, x)) + source(u(t, x), θ)
141+
bcs = [u(0, x) ~ sinpi(x), u(t, 0) ~ 0.0, u(t, 1) ~ 0.0]
142+
domains = [t ∈ Interval(0.0, 0.2), x ∈ Interval(0.0, 1.0)]
143+
ps = Any[parameters..., θ]
144+
@named pdesys = PDESystem(eq, bcs, domains, [t, x], [u(t, x)], ps)
145+
146+
disc = MOLFiniteDifference([x => 0.05], t)
147+
sys_arr, _ = symbolic_discretize(pdesys, disc)
148+
@test narrayeqs_interior(sys_arr) == 1
149+
if map_name !== nothing
150+
int_eq = only(filter(eq -> isinterioreq(eq) && isarrayeq(eq), get_eqs(sys_arr)))
151+
@test occursin(map_name, string(int_eq))
152+
end
153+
prob = discretize(pdesys, disc)
154+
@test prob isa SciMLBase.DAEProblem
155+
sol_arr = solve(prob)
156+
@test successful_retcode(sol_arr)
157+
xdisc = sol_arr[x]
158+
tdisc = sol_arr[t]
159+
exact = [exp((1 - pi^2) * ti) * sinpi(xi) for ti in tdisc, xi in xdisc]
160+
@test maximum(abs.(sol_arr[u(t, x)] .- exact)) < 1.0e-2
161+
return nothing
162+
end
163+
164+
@testset "1D diffusion, array parameter as scalar coefficient" begin
165+
test_parameterized_heat((u, θ) -> θ[1] * u)
166+
end
167+
168+
@testset "1D diffusion with parameterized registered function" begin
169+
test_parameterized_heat(
170+
(u, θ) -> vecfn_scalar(u, θ); map_name = "array_map_callable("
171+
)
172+
end
173+
174+
@testset "1D diffusion with vector-valued registered function" begin
175+
test_parameterized_heat(
176+
(u, θ) -> vecfn_array(u, θ)[1];
177+
map_name = "array_map_callable_getindex("
178+
)
179+
end
180+
181+
@testset "1D diffusion with callable vector parameter" begin
182+
@test ModelingToolkitBase.isparameter(Symbolics.unwrap(vecfn_parameter))
183+
test_parameterized_heat(
184+
(u, θ) -> vecfn_parameter(u, θ)[1];
185+
parameters = [vecfn_parameter],
186+
map_name = "array_map_callable_getindex("
187+
)
188+
end
189+
190+
@testset "Unsupported vector-parameter call falls back" begin
191+
@parameters t x
192+
@parameters θ[1:2] = [1.0, 0.0]
193+
@variables u(..)
194+
Dt = Differential(t)
195+
Dxx = Differential(x)^2
196+
197+
eq = Dt(u(t, x)) ~ Dxx(u(t, x)) + vecfn_rev(θ, u(t, x))
198+
bcs = [u(0, x) ~ sinpi(x), u(t, 0) ~ 0.0, u(t, 1) ~ 0.0]
199+
domains = [t ∈ Interval(0.0, 0.2), x ∈ Interval(0.0, 1.0)]
200+
@named pdesys = PDESystem(eq, bcs, domains, [t, x], [u(t, x)], [θ])
201+
202+
disc = MOLFiniteDifference([x => 0.05], t)
203+
sys, _ = symbolic_discretize(pdesys, disc)
204+
@test narrayeqs_interior(sys) == 0
205+
end
206+
207+
@testset "Vector-input callable parameter falls back and solves" begin
208+
@parameters t x
209+
@parameters θ[1:2] = [1.0, 0.0]
210+
@variables u(..)
211+
Dt = Differential(t)
212+
Dxx = Differential(x)^2
213+
214+
eq = Dt(u(t, x)) ~ Dxx(u(t, x)) + vecfn_parameter([u(t, x)], θ)[1]
215+
bcs = [u(0, x) ~ sinpi(x), u(t, 0) ~ 0.0, u(t, 1) ~ 0.0]
216+
domains = [t ∈ Interval(0.0, 0.2), x ∈ Interval(0.0, 1.0)]
217+
@named pdesys = PDESystem(
218+
eq, bcs, domains, [t, x], [u(t, x)], [vecfn_parameter, θ]
219+
)
220+
221+
disc = MOLFiniteDifference([x => 0.05], t)
222+
sys, _ = symbolic_discretize(pdesys, disc)
223+
@test narrayeqs_interior(sys) == 0
224+
prob = discretize(pdesys, disc)
225+
sol = solve(prob)
226+
@test successful_retcode(sol)
227+
xdisc = sol[x]
228+
tdisc = sol[t]
229+
exact = [exp((1 - pi^2) * ti) * sinpi(xi) for ti in tdisc, xi in xdisc]
230+
@test maximum(abs.(sol[u(t, x)] .- exact)) < 1.0e-2
231+
end
232+
114233
@testset "1D diffusion, Neumann and Robin BCs" begin
115234
@parameters t x
116235
@variables u(..)

0 commit comments

Comments
 (0)