MTK Easy way to get required states of observed state


Say I have an MTK model with a state x that is dependent on states y and z. After structural simplification x and it’s equation are moved to observed, y and z are still present in the simplified solution. I save the resultant sol to a CSV, so there’s columns for y and z but not x. I still have the sys in my “workspace” so I have access to the symbolic states, parameter values, and observed equations.

Now I want to load x from the CSV. My intent is to determine the other states required to solve the observed equation for x and load them to then solve for x. Is there a simple way for me to determine which states I’m required to load from the CSV (y and z) to solve the observed equation for x? Something like a get_required_states(x) returns [y,z].

Also, is there a simple way for me to search my observed equations for the equation of x? I’m sure I could achieve this through some parsing on my part but wanted to check if there’s a built-in method that’s more appropriate.

Alternatively, is there a way to save the ODE solution of the simplified equation, but also solve and save all observed equations so the data is readily available in the CSV file rather than calculating on load? Likely not what I want to do but just curious.


Of course right after making this post I found ModelingToolkit.get_variables which is exactly what I was looking for! Now I just need to find the method for easily identifying the observed equation of a variable.

1 Like


Just use a JLD2

Yea, JLD2 is exactly what I needed. Thanks Chris!

Quick follow up on this one. Let’s say I run an MTK monte carlo ensemble of 1000 runs with a system with 1000 states. I save the full ODE ensemble solution to JLD2 (rather than to CSVs per run). If I only want to load 1 state from each run, is there a way for JLD2 to support that, or do I need to load the full JLD2 with data for all of the states and runs?

With CSVs per run I’m able to load an individual state (column) from the run (csv file) which seems like it could save on load time over loading the full ensemble solution. If I’m looking to get the data for a state that was reduced, I can find the required variables for the observable equation using get_variables, then load that data, and find the observable equation. Once I have the numeric data and symbolic observed equation, how would I go about calculating the resultant observed state value? Symbolics.substitute seems like the answer but just checking in case there’s a better way.

Symbolics.substitute is probably the best way as of right now, other than maybe calling the observed function directly though that’s a bit risky as it’s not documented API.