How to copy variables from one optimized JuMP model into another model?

Hello everyone,

I’m working on a multi-period optimization problem using Julia, JuMP, and Ipopt. My approach involves solving individual time-step optimization subproblems as separate JuMP models (sub_model_t0), then intending to “copy” the solved decision variables from these sub-models into a “full” multi-period model (full_model).

I’ve run into some challenges with transferring variable values from the sub-models to the full model without re-defining variables or causing conflicts. I want to be able to access the variable values in the full model as if it had been optimized, even though I’ve only solved the sub-models.

Here’s a Minimal Working Example (MWE) illustrating the issue:

using JuMP
using Ipopt

# Time step
t0 = 3

# Build and solve sub_model_t0 for time step t0
sub_model_t0 = Model(Ipopt.Optimizer)
@variable(sub_model_t0, x1[t0] >= 0)
@variable(sub_model_t0, x2[t0] >= 0)
@objective(sub_model_t0, Min, (x1[t0] - 2)^2 + (x2[t0] - 5)^2)
optimize!(sub_model_t0)

# Adding variables from sub_model_t0 into full_model. 
# Let's assume it hasn't been created yet
full_model = Model(Ipopt.Optimizer)
# Unknown steps to copy the sub_model_t0 variables x1[t0], x2[t0] into full_model

# Intended outcome: I'm able to access the variables in full_model
# and their values (assuming we've somehow copied them over)
println("Value of x1[$(t0)] = $(value(full_model[:x1][t0]))")
println("Value of x2[$(t0)] = $(value(full_model[:x2][t0]))")

# Expected output:
# Value of x1[3] = 2.0
# Value of x2[3] = 5.0

# Note: full_model has not been optimized; it's used as a storage structure.

You cannot do this, and there is no work-around.

You must use a different data structure. For example, something like this:

variables = Dict{Symbol,Any}()
variables[:x1] = sub_model_t0[:x]
variables[:x2] = sub_model_t1[:x]
1 Like