Skip to content
Merged
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
22 changes: 16 additions & 6 deletions lib/ModelingToolkitBase/src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1201,14 +1201,27 @@ function is_numeric_symtype(T::Type)
return T <: Number || T <: AbstractArray && is_numeric_symtype(eltype(T))
end

"""
The concrete type of the graph returned by [`observed_dependency_graph`](@ref).
"""
const ObservedDependencyGraphT = DiCMOBiGraph{
false, Int, BipartiteGraph{Int, Nothing},
Matching{Unassigned, Vector{Union{Unassigned, Int}}},
}

"""
$(TYPEDSIGNATURES)

Return the `DiCMOBiGraph` denoting the dependencies between observed equations `eqs`.
"""
function observed_dependency_graph(sys::AbstractSystem, eqs::Vector{Equation})
function observed_dependency_graph(
sys::AbstractSystem, eqs::Vector{Equation}
)::ObservedDependencyGraphT
graph, assigns = observed2graph(sys, eqs, getproperty.(eqs, (:lhs,)))
matching = complete(Matching(Vector{Union{Unassigned, Int}}(assigns)))
# The unassigned type parameter is given explicitly instead of letting `Matching`
# infer it from the eltype, since that inference is not part of a stable contract
# and has differed between `BipartiteGraphs` versions.
matching = complete(Matching{Unassigned}(Vector{Union{Unassigned, Int}}(assigns)))
return DiCMOBiGraph{false}(graph, matching)
end

Expand All @@ -1219,10 +1232,7 @@ function should_invalidate_mutable_cache_entry(::Type{ObservedGraphCacheKey}, pa
end

struct ObservedGraphCache
graph::DiCMOBiGraph{
false, Int, BipartiteGraph{Int, Nothing},
Matching{Unassigned, Vector{Union{Unassigned, Int}}},
}
graph::ObservedDependencyGraphT
obsvar_to_idx::Dict{Any, Int}
end

Expand Down
11 changes: 11 additions & 0 deletions lib/ModelingToolkitBase/test/code_generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,14 @@ end
@mtkcomplete sys = System([D(y) ~ 2y + sum(x)], t, [y], []; observed = [x ~ [y, y + 1, y + 2]])
@test ModelingToolkitBase.observed_equations_used_by(sys, [x[1]]) == [1]
end

@testset "`observed_dependency_graph` result is cacheable" begin
@variables x(t) y(t) z(t)
@mtkcompile sys = System([D(x) ~ z, y ~ 2x + 1, z ~ 3y], t)
obs = ModelingToolkitBase.observed(sys)
graph = ModelingToolkitBase.observed_dependency_graph(sys, obs)
@test graph isa fieldtype(ModelingToolkitBase.ObservedGraphCache, :graph)
# this populates the observed graph cache, which requires the above type to match
@test ModelingToolkitBase.observed_equations_used_by(sys, [equations(sys)[1].rhs]) ==
[1, 2]
end
Loading