Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 50 additions & 14 deletions lib/ModelingToolkitBase/src/systems/connectors.jl
Original file line number Diff line number Diff line change
Expand Up @@ -345,23 +345,23 @@ end

#positivemax(m, ::Any; tol=nothing)= max(m, something(tol, 1e-8))
#_positivemax(m, tol) = ifelse((-tol <= m) & (m <= tol), ((3 * tol - m) * (tol + m)^3)/(16 * tol^3) + tol, max(m, tol))
const STREAM_EPS = 1.0e-4
function _stream_alpha(si)
return ifelse(si > STREAM_EPS, 1, ifelse(si > 0, (si / STREAM_EPS)^2 * (3 - 2 * si / STREAM_EPS), 0))
end
function _positivemax(m, si)
T = typeof(m)
relativeTolerance = 1.0e-4
nominal = one(T)
eps = relativeTolerance * nominal
alpha = if si > eps
one(T)
else
if si > 0
(si / eps)^2 * (3 - 2 * si / eps)
else
zero(T)
end
end
return alpha * max(m, 0) + (1 - alpha) * eps
alpha = _stream_alpha(si)
return alpha * max(m, 0) + (1 - alpha) * STREAM_EPS
end
@register_symbolic _positivemax(m, tol)
# At a positive-part kink, use the inactive branch's derivative.
Symbolics.@register_derivative _positivemax(m, si) 1 Symbolics.SConst(
_stream_alpha(si) * ifelse(m > 0, 1, 0)
)
Symbolics.@register_derivative _positivemax(m, si) 2 Symbolics.SConst(
ifelse((si > 0) & (si < STREAM_EPS), 6 * si / STREAM_EPS^2 * (1 - si / STREAM_EPS), 0) *
(max(m, 0) - STREAM_EPS)
)
positivemax(m, ::Any; tol = nothing) = _positivemax(m, tol)
mydiv(num, den) =
if den == 0
Expand Down Expand Up @@ -1506,3 +1506,39 @@ SymbolicUtils.promote_symtype(::typeof(instream_rt), _::SU.TypeT...) = Real
function SymbolicUtils.promote_shape(::typeof(instream_rt), @nospecialize(_::SU.ShapeT...))
return SU.ShapeVecT()
end

Symbolics.@register_derivative instream_rt(args...) I _instream_derivative(
SU.unwrap_const(args[1]), SU.unwrap_const(args[2]), args, I
)

function _instream_derivative(::Val{ni}, ::Val{no}, args, idx) where {ni, no}
idx <= 2 && return Symbolics.SConst(0)
flow_indices = [3:(2 + ni); (3 + 2 * ni):(2 + 2 * ni + no)]
stream_indices = [(3 + ni):(2 + 2 * ni); (3 + 2 * ni + no):length(args)]
si = Symbolics.SConst(0)
dsi = Symbolics.SConst(0)
for (j, fi) in enumerate(flow_indices)
flow = j <= ni ? -args[fi] : args[fi]
si += max(flow, 0)
if fi == idx
dsi = ifelse(flow > 0, j <= ni ? -1 : 1, 0)
end
end
num = den = dnum = dden = Symbolics.SConst(0)
for (fi, hi) in zip(flow_indices, stream_indices)
flow, stream = -args[fi], args[hi]
weight = _positivemax(flow, si)
dweight = (Symbolics.@derivative_rule _positivemax(flow, si) 2) * dsi
if fi == idx
dweight -= Symbolics.@derivative_rule _positivemax(flow, si) 1
end
num += weight * stream
den += weight
dnum += dweight * stream
if hi == idx
dnum += weight
end
dden += dweight
end
return Symbolics.SConst((dnum - num / den * dden) / den)
end
102 changes: 102 additions & 0 deletions lib/ModelingToolkitBase/test/instream_jacobian.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
function stream_finite_difference(f, x; step = 1.0e-5)
return reduce(
hcat, map(eachindex(x)) do i
xp, xm = copy(x), copy(x)
xp[i] += step
xm[i] -= step
(f(xp) - f(xm)) / (2 * step)
end
)
end

@testset "instream runtime derivatives" begin
for (ni, no) in [(2, 0), (3, 0), (1, 1), (2, 1)]
n = ni + no
@variables v[1:(2 * n)]
vars = collect(v)
flows = [1:ni; (2 * ni + 1):(2 * ni + no)]
streams = [(ni + 1):(2 * ni); (2 * ni + no + 1):(2 * n)]
term = SU.term(
ModelingToolkitBase.instream_rt, Val(ni), Val(no), vars...; type = Real
)
grad = Symbolics.gradient(Num(term), vars)
gradfun = Symbolics.build_function(grad, vars; expression = Val(false))[1]
runtime(x) = ModelingToolkitBase.instream_rt(Val(ni), Val(no), x...)
for flow in [-1.0, -5.0e-5, -1.0e-4 / n, -1.0e-5, 0.0, 1.0]
x = zeros(2 * n)
x[flows] .= flow
x[flows[(ni + 1):end]] .*= -1
x[streams] .= 2:(n + 1)
actual = gradfun(x)
@test all(isfinite, actual)
# Central differences converge linearly at the C¹ smoothing cutoff.
expected = vec(stream_finite_difference(runtime, BigFloat.(x); step = big"1e-20"))
@test actual ≈ expected atol = 1.0e-8 rtol = 1.0e-10
end
x = zeros(2 * n)
x[flows] .= -1.0
x[streams] .= 2:(n + 1)
x[first(flows)] = 0.0
@test all(isfinite, gradfun(x))
@test iszero(gradfun(x)[first(flows)])
end
end

if @isdefined(ModelingToolkit)
@connector function JacobianStreamPort(; name)
@variables p(t) m(t) [connect = Flow] h(t) [connect = Stream]
return System(Equation[], t, [p, m, h], []; name)
end

function JacobianStreamSource(; name, rate, start, variable_flow = false)
@named port = JacobianStreamPort()
@variables x(t) = start
eqs = [port.h ~ x, D(x) ~ -x]
if variable_flow
@variables q(t) = rate
append!(eqs, [port.m ~ -q, D(q) ~ -1])
else
push!(eqs, port.m ~ -rate)
end
return System(eqs, t; name, systems = [port])
end

function JacobianStreamReceiver(; name)
@named port = JacobianStreamPort()
@variables z(t) = 3.0
return System(
[port.p ~ 1.0, port.h ~ z, D(z) ~ instream(port.h) - z], t;
name, systems = [port]
)
end

@testset "Multi-source stream Jacobian" begin
for variable_flow in (false, true)
@named a = JacobianStreamSource(rate = 1.0, start = 2.0, variable_flow = variable_flow)
@named b = JacobianStreamSource(rate = 2.0, start = 4.0)
@named c = JacobianStreamReceiver()
sys = mtkcompile(
System(
[connect(a.port, b.port, c.port)], t;
name = :mixer, systems = [a, b, c]
)
)
prob = ODEProblem(sys, [], (0.0, 2.0); jac = true)
idx(v) = findfirst(isequal(v), unknowns(sys))
for rate in (variable_flow ? (1.0, -1.0) : (1.0,))
u = copy(prob.u0)
if variable_flow
u[idx(sys.a.q)] = rate
end
J = zeros(length(u), length(u))
prob.f.jac(J, u, prob.p, 1 - rate)
fd = stream_finite_difference(x -> prob.f(x, prob.p, 1 - rate), u)
@test J ≈ fd atol = 1.0e-8 rtol = 0
if !variable_flow
@test J[idx(sys.c.z), idx(sys.a.x)] ≈ 1 / 3
@test J[idx(sys.c.z), idx(sys.b.x)] ≈ 2 / 3
end
end
end
end
end
2 changes: 2 additions & 0 deletions lib/ModelingToolkitBase/test/stream_connectors.jl
Original file line number Diff line number Diff line change
Expand Up @@ -724,3 +724,5 @@ end
term = Symbolics.STerm(ModelingToolkitBase.instream_rt, [Val(1), Val(1), x, y, a, b]; type = Real, shape = UnitRange{Int}[])
@test isequal(term, SU.scalarize(term))
end

include("instream_jacobian.jl")
Loading