import mopeds
import numpy
variable_list = mopeds.VariableList()
variable_list.add_variable(mopeds.VariableAlgebraic("T", 373.0))
variable_list.add_variable(mopeds.VariableParameter("A", 3.55959, -1e3, 1e3))
variable_list.add_variable(mopeds.VariableParameter("B", 643.748, -1e3, 1e3))
variable_list.add_variable(mopeds.VariableParameter("C", -198.043, -1e4, 1e4))
variable_list.add_variable(mopeds.VariableControl("p", 1.0, 0.5, 3))
Variable List is an essential element of the mopeds package. It is a dictionary of all added variables. Variables are than accessed by a name.
Most variable classes have lower and upper bounds, for example, variable A is bounded from 1e-3 to 1e3. The bounds can be changed after creation.
print("Initial upper bound value: ", variable_list["A"].upper_bound)
Initial upper bound value: 1000.0
Since the variable list is a dictionary, you can iterate through variables and make complex changes, such as changing the lower and upper bounds of predefined variables:
for var_name, var in variable_list.items():
if isinstance(var, mopeds.VariableParameter):
var.lower_bound = -1e4
var.upper_bound = 1e4
for var in variable_list.values():
print(var.name, var.lower_bound, var.upper_bound)
T -inf inf A -10000.0 10000.0 B -10000.0 10000.0 C -10000.0 10000.0 p 0.5 3
Model¶
Next we create a model instance based on a variable list, add equations and finalize the model by providing a list of equations.
Model keeps track of all available variables and their casadi symbols, accessible using the .casadi_var attribute.
m = mopeds.Model(variable_list)
T = m.varlist_all["T"].casadi_var
A = m.varlist_all["A"].casadi_var
B = m.varlist_all["B"].casadi_var
C = m.varlist_all["C"].casadi_var
p = m.varlist_all["p"].casadi_var
EQ_alg1 = p - 10 ** (A - (B / (T + C)))
list_algebraic_equations = [EQ_alg1]
m.add_equations_algebraic(list_algebraic_equations)
Simulator¶
At this point we have a model ready for the first evaluation. To do this, we need to create a simulator instance and solve the system.
The system is solved for a pressure variable p specified during creation.
sim = mopeds.SimulatorNLE(m, variable_list)
print(sim.simulate_fast())
{'x': DM(378.892)}
Simulator evaluates based on the values provided by the variable list. They are then stored in the ._independent_variables attribute of the simulator. To change values of independent variables you can use top level method change_independent_variables or change them manually.
The mapping of the variable names to a position of the variable is given in the .mapping_independent_variables dictionary.
print("Mapping of independent variables", sim.mapping_independent_variables)
print("Values of independent variables", sim._independent_variables)
index_of_p = sim.mapping_independent_variables["p"]
sim.change_independent_variables({"p": 2})
T_value = sim.simulate_fast()["x"]
print(
f"At pressure {sim._independent_variables[index_of_p]} bar the temperature equals {T_value}"
)
sim._independent_variables[index_of_p] = 3
T_value = sim.simulate_fast()["x"]
print(
f"At pressure {sim._independent_variables[index_of_p]} bar the temperature equals {T_value}"
)
Mapping of independent variables {'A': 0, 'B': 1, 'C': 2, 'p': 3}
Values of independent variables [0.000355959, 0.0643748, -0.0198043, -0.6]
At pressure 0.2 bar the temperature equals 395.599
At pressure 3 bar the temperature equals 426.385
In a given example, there is only one return value of the simulate_fast() method. If you have more variables, you can now use mapping of algebraic variables to get the index of each variable in the result. Or use a top-level method to return a variable list with results.
print("Mapping of algebraic variables", sim.mapping_algebraic_variables)
res_varlist = sim.simulate()[2]
print(res_varlist["T"])
print(res_varlist["T"].value[0])
Mapping of algebraic variables {'T': 0}
T
<class 'mopeds.variables.VariableAlgebraic'>
[426.38499910063825]
426.38499910063825
With more variables in the model, it is easier to use Pandas Dataframe to display variables and their values. The NaN value of the variable T means that it doesn't have a value because it needs to be calculated. The previously specified value 373 is used as a guess for the root finder.
print("Guess value of T", variable_list["T"].guess)
variable_list.dataframe
Guess value of T 373.0
| T | A | B | C | p | |
|---|---|---|---|---|---|
| 1970-01-01 | NaN | 3.55959 | 643.748 | -198.043 | 1.0 |
Troubleshooting¶
If you the system cannot be solved, you will get a casadi error. For example if we set a guess for temperature to 198.043 (-C value), there will be zero in the denominator during the first iteration of the rootfinder. The j=Jacobian cannot be evaluated, resulting in NaN in nlpsol:nlp_jac_g.
index_T = sim.mapping_algebraic_variables["T"]
sim.call_arg["x0"][index_T] = 198.043
sim.simulate()
CasADi - 2024-02-20 17:23:15 WARNING("nlpsol:nlp_jac_g failed: NaN detected for output jac_g_x, at (row 0, col 0).") [.../casadi/core/oracle_function.cpp:377]
CasADi - 2024-02-20 17:23:15 WARNING("nlpsol:nlp_jac_g failed: NaN detected for output jac_g_x, at (row 0, col 0).") [.../casadi/core/oracle_function.cpp:377]
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) /var/folders/jr/5dw64dfd6dd99gw_9psdv2kr0000gn/T/ipykernel_58671/3641481347.py in ?() 1 index_T = sim.mapping_algebraic_variables["T"] 2 sim.call_arg["x0"][index_T] = 198.043 ----> 3 sim.simulate() ~/repos/mopeds/src/mopeds/variables.py in ?(self, *args, **kwargs) 48 def _decorator(self, *args, **kwargs): 49 if get_options()["variable_scaling"] != self._created_with_options["variable_scaling"]: 50 print("User provided scaling is ignored, because object was created with another scaling") 51 with options(variable_scaling=self._created_with_options["variable_scaling"]): ---> 52 return func(self, *args, **kwargs) ~/repos/mopeds/src/mopeds/simulation_nle.py in ?(self, return_var_names, unfixed_variables, return_varlist) 238 @_consistent_scaling_decorator 239 def simulate(self, *, return_var_names: list[str] | None = None, unfixed_variables: dict[str, float] | None = None, return_varlist: bool = True) -> ca.DM | ca.MX: 240 """Wrapper for simulate_fast, that returns scaled results. 241 res is returned as dict to be consistent with Dynamic simulations.""" --> 242 res = self.simulate_fast() 243 res_selected = self.select_simulation_result(res, return_var_names) 244 245 if not isinstance(res["x"], ca.DM): ~/repos/mopeds/src/mopeds/simulation_nle.py in ?(self) 287 def simulate_fast(self) -> dict[str, ca.MX | ca.DM]: 288 """Should be used internally for fast calculations. Output of the solution is not scaled""" 289 self.call_arg["p"] = self._independent_variables 290 --> 291 res = self._call_simulator() 292 return res ~/repos/mopeds/src/mopeds/simulation_nle.py in ?(self) 210 def __call_simulator_rootfinder(self) -> ca.DM: 211 """This method is needed to raise an error, if ipopt simulator fails to converge""" --> 212 return self.simulator.call(self.call_arg) ~/.pyenv/versions/mopeds/lib/python3.12/site-packages/casadi/casadi.py in ?(self, *args) 20035 20036 20037 20038 """ > 20039 return _casadi.Function_call(self, *args) RuntimeError: Error in Function::call for 's' [ImplicitToNlp] at .../casadi/core/function.cpp:1401: Error in Function::call for 's' [ImplicitToNlp] at .../casadi/core/function.cpp:330: .../casadi/core/rootfinder.cpp:278: rootfinder process failed. Set 'error_on_fail' option to false to ignore this error.