Coverage for examples/SimpleBuilding/mpc_and_sim/simple_building.py: 67%
15 statements
« prev ^ index » next coverage.py v7.4.4, created at 2025-10-20 14:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2025-10-20 14:09 +0000
1from agentlib_mpc.models.casadi_model import (
2 CasadiModel,
3 CasadiInput,
4 CasadiState,
5 CasadiParameter,
6 CasadiOutput,
7 CasadiModelConfig,
8)
9from math import inf
11class BaselineMPCModelConfig(CasadiModelConfig):
13 inputs: list[CasadiInput] = [
14 # controls
15 # Power var needs to be declared as an output. Here power var is also a model-input
16 # So two separate var names are used for power var: P_in as input, P_el as output
17 # P_el set to P_in below
18 CasadiInput(
19 name="P_in",
20 value=100,
21 unit="W",
22 description="Electrical power of heating rod (equivalent to P_el)",
23 ),
24 # disturbances
25 CasadiInput(
26 name="T_amb",
27 value=290.15,
28 unit="K",
29 description="Ambient air temperature",
30 ),
31 # settings
32 CasadiInput(
33 name="T_upper",
34 value=294.15,
35 unit="K",
36 description="Upper boundary (soft) for T",
37 ),
38 CasadiInput(
39 name="T_lower",
40 value=290.15,
41 unit="K",
42 description="Lower boundary (soft) for T",
43 ),
44 ]
46 states: list[CasadiState] = [
47 # differential
48 CasadiState(
49 name="T_zone",
50 value=293.15,
51 unit="K",
52 description="Temperature of zone",
53 ),
54 # algebraic
55 # slack variables
56 CasadiState(
57 name="T_slack",
58 value=0,
59 unit="K",
60 description="Slack variable for zone temperature",
61 ),
62 ]
64 parameters: list[CasadiParameter] = [
65 CasadiParameter(
66 name="C",
67 value=10000,
68 unit="J/K",
69 description="Thermal capacity of zone",
70 ),
71 CasadiParameter(
72 name="U",
73 value=5,
74 unit="W/K",
75 description="Thermal conductivity of zone",
76 ),
77 CasadiParameter(
78 name="s_T",
79 value=1,
80 unit="-",
81 description="Weight for zone temperature slack var in constraint function",
82 ),
83 CasadiParameter(
84 name="r_pel",
85 value=1,
86 unit="-",
87 description="Weight for P_el in objective function",
88 )
89 ]
91 outputs: list[CasadiOutput] = [
92 CasadiOutput(
93 name="P_el",
94 unit="W",
95 description="Electrical power of heating rod (system input)",
96 )
97 ]
99class BaselineMPCModel(CasadiModel):
101 config: BaselineMPCModelConfig
103 def setup_system(self):
104 # Define ode
105 self.T_zone.ode = (self.P_in - self.U * (self.T_zone - self.T_amb)) / self.C
107 #Define ae for outputs
108 self.P_el.alg = self.P_in
110 # Constraints: list[(lower bound, function, upper bound)]
111 self.constraints = [
112 # soft constraints
113 (-inf, self.T_zone - self.T_slack, self.T_upper),
114 (self.T_lower, self.T_zone + self.T_slack, inf),
115 (0, self.T_slack, inf),
116 # hard constraints
117 (0, self.P_in, 200),
118 ]
120 # Objective function
121 objective = sum(
122 [
123 self.s_T * self.T_slack**2,
124 self.r_pel * self.P_in,
125 ]
126 )
128 return objective