JuliaMPC / NLOptControl.jl

nonlinear control optimization tool
Other
109 stars 26 forks source link

Saving unscaled variables #34

Closed mfalt closed 3 years ago

mfalt commented 3 years ago

Since the variables saved in OCPResults.x is no longer actual JuMP.Variables but the scaled variables and thus NLExpressions, there are no longer any references left to the actual JuMP variables. This makes it really hard to set the initial guess of the solution. This PR adds back these references. This makes it possible to set the initial guess, for example using the following code (at least for some model types):


function set_guess!(n, t, states, controls, tf)
    x = n.r.ocp.xUnscaled
    u = n.r.ocp.uUnscaled
    N = size(x,1)           # Number of time steps in optimization problem
    nx = size(states,2)     # Number of states
    nu = size(controls,2)   # Number of controls
    @assert nx == size(x,2) # Guess and problem have same number of states
    @assert nu == size(u,2) # Guess and problem have same number of inputs
    @assert size(states,1) == size(states,1) == length(t) # Guess has right lengths
    # Set finial time guess
    setvalue(n.ocp.tf, tf)
    for i = 1:nx # For each state
        # Interpolate guess based on time t
        xi = interpolate((t,), states[:,i], Gridded(Linear()))
        for j = 1:N                     # For each time point
            tj = tf/(N-1)*(j-1)             # Time of gridpoint j
            setvalue(x[j,i], xi(tj))    # Set guess
        end
    end
    # Set control guess
    for i = 1:nu
        ui = interpolate((t,), controls[:,i], Gridded(Linear()))
        for j = 1:N
            tj = tf/(N-1)*(j-1)
            setvalue(u[j,i], ui(tj))
        end
    end
    return
end