Skip to content

Commit aa6f340

Browse files
feat: add assertions support to debug_system
1 parent 5f8cda3 commit aa6f340

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/debugging.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,21 @@ function debug_sub(ex, funcs; kw...)
4242
f in funcs ? logged_fun(f, args...; kw...) :
4343
maketerm(typeof(ex), f, args, metadata(ex))
4444
end
45+
46+
function _debug_assertion(expr::Bool, message::String, log::Bool)
47+
expr && return 0.0
48+
log && @error message
49+
return NaN
50+
end
51+
52+
@register_symbolic _debug_assertion(expr::Bool, message::String, log::Bool)
53+
54+
const ASSERTION_LOG_VARIABLE = only(@parameters __log_assertions_ₘₜₖ::Bool = false)
55+
56+
function get_assertions_expr(assertions::Dict{BasicSymbolic, String})
57+
term = 0
58+
for (k, v) in assertions
59+
term += _debug_assertion(k, "Assertion $k failed:\n$v", ASSERTION_LOG_VARIABLE)
60+
end
61+
return term
62+
end

src/systems/abstractsystem.jl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2312,7 +2312,15 @@ function debug_system(
23122312
error("debug_system(sys) only works on systems with no sub-systems! Consider flattening it with flatten(sys) or structural_simplify(sys) first.")
23132313
end
23142314
if has_eqs(sys)
2315-
@set! sys.eqs = debug_sub.(equations(sys), Ref(functions); kw...)
2315+
eqs = debug_sub.(equations(sys), Ref(functions); kw...)
2316+
expr = get_assertions_expr(assertions(sys))
2317+
eqs[end] = eqs[end].lhs ~ eqs[end].rhs + expr
2318+
@set! sys.eqs = eqs
2319+
@set! sys.ps = unique!([get_ps(sys); ASSERTION_LOG_VARIABLE])
2320+
@set! sys.defaults = merge(get_defaults(sys), Dict(ASSERTION_LOG_VARIABLE => true))
2321+
if iscomplete(sys)
2322+
sys = complete(sys; split = is_split(sys))
2323+
end
23162324
end
23172325
if has_observed(sys)
23182326
@set! sys.observed = debug_sub.(observed(sys), Ref(functions); kw...)

0 commit comments

Comments
 (0)