# ModelingToolkit and State Variables with Optimization

**URL:** <https://discourse.julialang.org/t/modelingtoolkit-and-state-variables-with-optimization/84430>\
**Category:** Modelling & Simulations\
**Tags:** optimization, modelingtoolkit\
**Created:** [July 18, 2022, 10:26pm UTC](https://discourse.julialang.org/t/modelingtoolkit-and-state-variables-with-optimization/84430 "2022-07-18T22:26:28Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![lamorton](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lamorton/32/21115_2.png) [@lamorton](https://discourse.julialang.org/u/lamorton)\
**Post date:** [October 8, 2022, 12:20am UTC](https://discourse.julialang.org/t/modelingtoolkit-and-state-variables-with-optimization/84430/11 "2022-10-08T00:20:56Z")

</div>

@RGon Yeah, I think that’s the end goal. It’s possible to use MTK that way right now (I’ve done it to some approximation) but it requires a fair amount of hacking. For starters, you need to avoid using symbolic indexing in the loss function, which means that you need to have a loss function factory that finds the index of the state variables that you want to derive the loss from, and then capture that indexer in the loss function. (See the [FAQ](https://github.com/SciML/ModelingToolkit.jl/blob/master/docs/src/basics/FAQ.md#using-modelingtoolkit-with-optimization--automatic-differentiation)). Also, if you need an observed variable, you have to get the observation function and capture it too. Finally, if you want some parameters to be adjustable & others not, you need to do more indexing tricks to interpolate the values of the adjustable subset into the full parameter vector & fill the rest with the default values. More indexing is required if you want to [override the default value](https://discourse.julialang.org/t/is-there-a-way-to-change-a-single-parameter-in-am-odeproblem-and-rerun-it/86775/4) of a parameter.

I think the plan for the future involves fixing at least some of those inconveniences. For instance, to toggle the adjustability of a parameter, there’s [going to be a metadata flag](https://discourse.julialang.org/t/parameter-tunability/87756) that will tell optimizers not to adjust a parameter. There may also be some work on [getting observed variables](https://github.com/SciML/ModelingToolkit.jl/issues/1102) more efficiently. IDK if that will help with automatic differentiation though.

---

_[View the full topic](https://discourse.julialang.org/t/modelingtoolkit-and-state-variables-with-optimization/84430)._
