# 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:** 16

<div class="post-metadata">

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

</div>

@yhchang PS. A quick try at your problem with `OptimalControl.jl`:

```julia
const τ = 1.0
const σ = 49.0
const fmax = 10.0
const T = 20.0
const e0 = 100.0

ocp = @def begin
    t ∈ [0, T], time
    x = (v, e) ∈ R², state
    f ∈ R, control
    ẋ(t) == [-v(t) / τ + f(t), σ - f(t) * v(t)]
    v(0) == 0
    e(0) == e0
    0 ≤ f(t) ≤ fmax
    e(t) ≥ 0
    ∫( -v(t) ) → min
end

N = 1000
tol = 1e-4

sol = solve(ocp; grid_size=N, tol=tol)
plot(sol)

```

Playing a bit with the solver tolerance (Ipopt here, you may also try, _e.g._, MadNLP) gets a similar result to what @odow sent:

 ![IMG_4003](https://global.discourse-cdn.com/julialang/original/3X/8/1/8189e02c915de6850c83b2dbd971f87e8b580fa1.jpeg)

The expected oscillation at the junction between the bang and singular arc can be further accommodated using a simple L^2 regularisation:

```julia
ocp_r(ε) = @def begin
    t ∈ [0, T], time
    x = (v, e) ∈ R², state
    f ∈ R, control
    ẋ(t) == [-v(t) / τ + f(t), σ - f(t) * v(t)]
    v(0) == 0
    e(0) == e0
    0 ≤ f(t) ≤ fmax
    e(t) ≥ 0
    ∫( -v(t) + ε * f(t)^2 ) → min
end

ε = 1e-4 # L^2 regularisation

sol_r = solve(ocp_r(ε); grid_size=N)
plot(sol_r)

```

 ![IMG_4002](https://global.discourse-cdn.com/julialang/original/3X/5/7/5781c8961bb82fc9f74ad0f0928e9bacf414f791.jpeg)

---

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