Skip to content

Commit e999ecd

Browse files
committed
Integrate objective terms outside modelica to not harm optimization.
1 parent 2037a51 commit e999ecd

1 file changed

Lines changed: 17 additions & 2 deletions

File tree

wedoco_optimo/model.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,9 @@ def define_optimization(self,
222222
ipopt_options: dict=None,
223223
prescribed_inputs: dict=None):
224224

225+
# Assign objective terms
226+
self.objective_terms = objective_terms if objective_terms is not None else []
227+
225228
# Initialize the optimization problem if not already done.
226229
if not hasattr(self, "ocp"):
227230
self.initialize_optimization(ipopt_options=ipopt_options, prescribed_inputs=prescribed_inputs)
@@ -247,7 +250,7 @@ def define_optimization(self,
247250
self.ocp.set_t0(0)
248251

249252
# Formulate objective from provided list of objective terms
250-
for term in objective_terms:
253+
for term in self.objective_terms:
251254
self.ocp.add_objective(self.ocp.integral(self.f_xu_xyu(x=self.x, u=self.u)['y'][self.dae.y().index(term)]))
252255

253256
# Set constraints
@@ -260,7 +263,7 @@ def define_optimization(self,
260263
for prescribed_input in prescribed_inputs.keys():
261264
self.ocp.set_value(self.dae.var(prescribed_input), prescribed_inputs[prescribed_input])
262265

263-
def optimize(self):
266+
def optimize(self, calculate_objective_terms_integrals: bool=True):
264267

265268
# Solve the optimization problem
266269
try:
@@ -278,6 +281,18 @@ def optimize(self):
278281
u_ocp = res_xyu_ocp["u"].full()
279282

280283
t0 = 0
284+
281285
res_df = get_dae_results(t_ocp, self.dae, x_ocp, y_ocp, u_ocp, t0)
282286

287+
if calculate_objective_terms_integrals:
288+
# Calculate the cumulative integrated objective terms over the horizon
289+
for term in self.objective_terms:
290+
term_index = self.dae.y().index(term)
291+
term_values = y_ocp[term_index, :]
292+
dt_array = np.diff(t_ocp, prepend=t0)
293+
# Calculate cumulative integral (cumulative sum of term_values * dt_array)
294+
integral_array = np.cumsum(term_values * dt_array)
295+
# Add the integrated term to the results as a new variable
296+
res_df[f"{term}Int"] = integral_array
297+
283298
return res_df

0 commit comments

Comments
 (0)