|
| 1 | +# # [Parameters](@id parameters) |
| 2 | +# Parameters act like fixed variables. Internally, ExaModels keeps track of where parameters appear in the model, making it possible to efficiently modify their value without rebuilding the entire model. |
| 3 | + |
| 4 | +# ### Creating Parametric Models |
| 5 | +# |
| 6 | +# Let's modify the example in [Getting Started](@ref guide) to use parameters. Suppose we want to make the penalty coefficient in the objective function adjustable: |
| 7 | + |
| 8 | +# First, let's create a core: |
| 9 | +using ExaModels, NLPModelsIpopt |
| 10 | +c_param = ExaCore() |
| 11 | + |
| 12 | +# Adding parameters is very similar to adding variables -- just pass a vector of values denoting the initial values. |
| 13 | +θ = parameter(c_param, [100.0, 1.0]) # [penalty_coeff, offset] |
| 14 | + |
| 15 | +# Define the variables as before: |
| 16 | +N = 10 |
| 17 | +x_p = variable(c_param, N; start = (mod(i, 2) == 1 ? -1.2 : 1.0 for i = 1:N)) |
| 18 | + |
| 19 | +# Now we can use the parameters in our objective function just like variables: |
| 20 | +objective(c_param, θ[1] * (x_p[i-1]^2 - x_p[i])^2 + (x_p[i-1] - θ[2])^2 for i = 2:N) |
| 21 | + |
| 22 | +# Add the same constraints as before: |
| 23 | +constraint( |
| 24 | + c_param, |
| 25 | + 3x_p[i+1]^3 + 2 * x_p[i+2] - 5 + sin(x_p[i+1] - x_p[i+2])sin(x_p[i+1] + x_p[i+2]) + 4x_p[i+1] - |
| 26 | + x_p[i]exp(x_p[i] - x_p[i+1]) - 3 for i = 1:(N-2) |
| 27 | +) |
| 28 | + |
| 29 | +# Create the model as before: |
| 30 | +m_param = ExaModel(c_param) |
| 31 | + |
| 32 | +# Solve with original parameters: |
| 33 | +result1 = ipopt(m_param) |
| 34 | +println("Original objective: $(result1.objective)") |
| 35 | + |
| 36 | +# Now change the penalty coefficient and solve again: |
| 37 | +set_parameter!(c_param, θ, [200.0, 1.0]) # Double the penalty coefficient |
| 38 | +result2 = ipopt(m_param) |
| 39 | +println("Modified penalty objective: $(result2.objective)") |
| 40 | + |
| 41 | +# Try a different offset parameter: |
| 42 | +set_parameter!(c_param, θ, [200.0, 0.5]) # Change the offset in the objective |
| 43 | +result3 = ipopt(m_param) |
| 44 | +println("Modified offset objective: $(result3.objective)") |
0 commit comments