# Optimizing a function in optimal control problem

**URL:** <https://discourse.julialang.org/t/optimizing-a-function-in-optimal-control-problem/125483>\
**Category:** Optimization (Mathematical)\
**Tags:** optimization, sciml, differentialequation\
**Created:** [February 2, 2025, 9:34pm UTC](https://discourse.julialang.org/t/optimizing-a-function-in-optimal-control-problem/125483 "2025-02-02T21:34:14Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [February 2, 2025, 9:48pm UTC](https://discourse.julialang.org/t/optimizing-a-function-in-optimal-control-problem/125483/2 "2025-02-02T21:48:40Z")

</div>

> [@yhchang](#):
>
> `f = LinearInterpolation(f_interp, t_interp)(t)`

This is really going to hurt the performance of the ODE solver because it makes the integrand non-smooth. I would parameterize f(t) in a smooth way if possible.

For example, you could parameterize f(t) = \left[\tanh(p(2t/T - 1)) + 1\right] f\_\max / 2 where p(x) is a polynomial in a Chebyshev basis on x\in [-1,1] (which allow you to go to very high degree without problems), with unconstrained coefficients. The tanh function ensures that f(t) \in (0, f\_\max).

See also [ODE non autonomous interpolation needed - #5 by ChrisRackauckas](https://discourse.julialang.org/t/ode-non-autonomous-interpolation-needed/125175/5) …

> [@yhchang](#):
>
> `optprob = OptimizationFunction(cost_fun, Optimization.AutoForwardDiff()`

Forward-mode AD is also going to hurt you here because its cost scales with the number of parameters, so computing your derivatives here will be ≈ 200x the cost of solving the ODE once. You really want to use reverse-mode (either via AD or via manual adjoint equations — see our [course notes, chapter 9](https://arxiv.org/abs/2501.14787) — or with the help of SciMLSensitivity.jl) in this kind of problem if possible.

---

_[View the full topic](https://discourse.julialang.org/t/optimizing-a-function-in-optimal-control-problem/125483)._
