Skip to content

Commit d954c7a

Browse files
Merge pull request #4691 from KristofferC/kc/cache_getu_call
cache the `concrete_getu` call
2 parents 079e236 + 1a199be commit d954c7a

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

lib/ModelingToolkitBase/src/systems/problem_utils.jl

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -872,6 +872,30 @@ Base.@nospecializeinfer function __specialize_templates(template::Vector{Any}, e
872872
end
873873
end
874874

875+
# Memo for the symbolic-fallback getters built by `CopyParamsByTemplate`. The init problem
876+
# builds several `CopyParamsByTemplate`s over the same `initsys` (e.g. `GetUpdatedU0` and the
877+
# `initializeprobmap`)
878+
abstract type TemplateGetuCache end
879+
const TemplateGetuCacheT = Dict{Vector{SymbolicT}, Any}
880+
881+
function should_invalidate_mutable_cache_entry(::Type{TemplateGetuCache}, @nospecialize(patch::NamedTuple))
882+
return false
883+
end
884+
885+
function cached_template_getu(srcsys::AbstractSystem, batch::Vector{SymbolicT}; kws...)
886+
if !(srcsys isa System)
887+
return concrete_getu(srcsys, Symbolics.SConst(batch); wrap_as_any = true, kws...)
888+
end
889+
cache = check_mutable_cache(srcsys, TemplateGetuCache, TemplateGetuCacheT, nothing)
890+
if cache === nothing
891+
cache = TemplateGetuCacheT()
892+
store_to_mutable_cache!(srcsys, TemplateGetuCache, cache)
893+
end
894+
return get!(cache, batch) do
895+
concrete_getu(srcsys, Symbolics.SConst(batch); wrap_as_any = true, kws...)
896+
end
897+
end
898+
875899
function CopyParamsByTemplate(srcsys::AbstractSystem, syms::AbstractArray{SymbolicT}; kws...)
876900
template = []
877901
elem_types = Set{DataType}()
@@ -976,7 +1000,7 @@ function CopyParamsByTemplate(srcsys::AbstractSystem, syms::AbstractArray{Symbol
9761000

9771001
for i in eachindex(template)
9781002
if template[i] isa Vector{SymbolicT}
979-
template[i] = concrete_getu(srcsys, Symbolics.SConst(template[i]); wrap_as_any = true, kws...)
1003+
template[i] = cached_template_getu(srcsys, template[i]; kws...)
9801004
delete!(elem_types, Vector{SymbolicT})
9811005
push!(elem_types, typeof(template[i]))
9821006
end

0 commit comments

Comments
 (0)