"ACADOS and CasADi Error: Initialization failed for 'ev_ocp_cost_ext_cost_e_fun' due to free variables

Hi everyone,

I’m working on an optimization problem using ACADOS and CasADi to model the state of charge (SOC) of electric vehicles (EVs). My goal is to optimize the charging and discharging of EVs over a given time horizon. However, I encountered the following error while setting up and running the solver:

Error in Function::Function for 'ev_ocp_cost_ext_cost_e_fun' [SXFunction] at .../casadi/core/function.cpp:240:
.../casadi/core/function_internal.cpp:146: Error calling SXFunction::init for 'ev_ocp_cost_ext_cost_e_fun':
.../casadi/core/sx_function.cpp:476: ev_ocp_cost_ext_cost_e_fun::init: Initialization failed since variables [P_vehicle_0P_vehicle_1P_vehicle_2] are free.
These symbols occur in the output expressions but you forgot to declare these as inputs. Set option 'allow_free' to allow free variables.

State Variables (x): SOC (State of Charge) of the EVs.
Control Variables (u): Charging/discharging power for each vehicle.(P_vehicle)
Parameters ( PV_ power,price_buy: Electricity purchase price,price_sell: Electricity selling price.)

I defined the cost function as follows:

P_grid = sum(P_vehicle) - P_PV;
stage_cost = price_buy * max(P_grid, 0) - price_sell * max(-P_grid, 0);

What I have tried:

  1. Defining the Control Variable:I added the control variable to the model structure
    2)Assigning the Cost Function
    3)Allowing Free Variables

Questions:

  1. Why is the control variable (P_vehicle)identified as “free variables” in this context?

2)What could I be missing in defining the control variables or passing them to the solver?

  1. How can I correctly resolve this issue without relying on allow_free?

Thanks

Hi :wave:

the problem occurs since the terminal cost can not depend on the control. I assume you set both the stage cost and the terminal cost to the same expression, instead you need to provide an expression for the terminal cost which only depends on the state.

Best, Katrin

1 Like

And since your cost is linear, you will need some regularization, e.g. regularize_method = 'PROJECT', and maybe also globalization :slight_smile:

1 Like