ModelingToolkit.jl icon indicating copy to clipboard operation
ModelingToolkit.jl copied to clipboard

How can I write a generated function expression to file?

Open asinghvi17 opened this issue 3 months ago • 2 comments

Given a System sys, you can obtain a serializable problem expression via:

import ModelingToolkit as MTK
# sys = ...
prob_expr = MTK.ODEProblem{true, MTK.SciMLBase.FullSpecialize}(sys2, [], (0.0, 3000.0); expression = Val{true})

where prob_expr isa Expr. But when I try to write this to file, it also dumps the printed representation of the system as well as some invocation of remake. How can I just get an expr that defines the runtime generated function, that I can write to file, and then load via include without manual edits?

The main reason for this is performance tuning. It is impossible to profile the mathematical operations of a problem at this point, because they don't include line number information (so the profiler refuses to show them). The simple solution is to write them to file (the longer solution involves provenance etc. which is quite tedious to actually do).

asinghvi17 avatar Aug 31 '25 11:08 asinghvi17

You can use generate_rhs(sys)

SebastianM-C avatar Aug 31 '25 12:08 SebastianM-C

Thanks! That works.

For future reference:

iip_expr, oop_expr = MTK.generate_rhs(sys);

Then you can write to and include it from file:

write("expr.jl", sprint(Base.show_unquoted, oop_expr))
f_oop = include("expr.jl")

Would be nice to have this in the docs as well!

asinghvi17 avatar Aug 31 '25 14:08 asinghvi17