# Nested optimization

**URL:** <https://discourse.julialang.org/t/nested-optimization/26061>\
**Category:** Optimization (Mathematical)\
**Created:** [July 6, 2019, 12:00am UTC](https://discourse.julialang.org/t/nested-optimization/26061 "2019-07-06T00:00:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Farnazmdi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/farnazmdi/32/24072_2.png) [@Farnazmdi](https://discourse.julialang.org/u/Farnazmdi)\
**Post date:** [July 6, 2019, 12:00am UTC](https://discourse.julialang.org/t/nested-optimization/26061/1 "2019-07-06T00:00:34Z")

</div>

Hi,  
I have a model from which I estimate some parameters, and the parameters are “data” to my second model. I want to be able to optimize the parameters of the first model in a way that the second model fits well. Since `optimize` just takes functions (cost functions) I cannot write both optimizations right after another in one function. Is there any specific package in Julia for this kind of optimization?

```julia
function DEmodel()
     ....
end

function DEsolve()
...
end

function second_model()
... [it is just a curve fit, not a DE model]
end

function residuals_to_firstModel()
DEmodel() - data
end

r = optimize(residuals_to_firstModel, initial, LevenbergMarquardt())
parameters = r.minimizer

function residuals_to_secondModel()
second_model() - parameters
end
p = optimize(residuals_to_secondModel, initial, LevenbergMarquardt())

```

I don’t know how to make a loop so that the second model’s goodness of fit, feedbacks to the first model to adjust the parameters.

I appreciate any ideas!

---

<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:** [July 6, 2019, 1:34am UTC](https://discourse.julialang.org/t/nested-optimization/26061/2 "2019-07-06T01:34:16Z")

</div>

> [@Farnazmdi](#):
>
> I don’t know how to make a loop so that the second model’s goodness of fit, feedbacks to the first model to adjust the parameters.

Don’t use a loop. Optimize all of the parameters simultaneously. That is, minimize `residuals_to_secondModel` as a function of the parameters of _both_ models.

---

<div class="post-metadata">

**Author:** ![Farnazmdi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/farnazmdi/32/24072_2.png) [@Farnazmdi](https://discourse.julialang.org/u/Farnazmdi)\
**Post date:** [July 6, 2019, 6:16pm UTC](https://discourse.julialang.org/t/nested-optimization/26061/3 "2019-07-06T18:16:19Z")

</div>

Thank you
