Skip to content

Commit

Permalink
Merge pull request #237 from do-mpc/develop
Browse files Browse the repository at this point in the history
v4.3.3
  • Loading branch information
4flixt committed Feb 14, 2022
2 parents 3a930e2 + 495a052 commit 1a44d39
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 17 deletions.
13 changes: 10 additions & 3 deletions do_mpc/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,11 +616,18 @@ def set_objective(self, mterm=None, lterm=None):
if not isinstance(lterm, (casadi.DM, casadi.SX, casadi.MX)):
raise Exception('lterm must be of type casadi.DM, casadi.SX or casadi.MX. You have: {}.'.format(type(lterm)))

self.mterm = mterm
if mterm is None:
self.mterm = DM(0)
else:
self.mterm = mterm
# TODO: This function should be evaluated with scaled variables.
self.mterm_fun = Function('mterm', [_x, _tvp, _p], [mterm])

self.lterm = lterm
if lterm is None:
self.lterm = DM(0)
else:
self.lterm = lterm

self.lterm_fun = Function('lterm', [_x, _u, _z, _tvp, _p], [lterm])

# Check if lterm and mterm use invalid variables as inputs.
Expand Down Expand Up @@ -1144,7 +1151,7 @@ def _prepare_nlp(self):
self.ub_opt_x = opt_x(np.inf)

# Initialize objective function and constraints
obj = 0
obj = DM(0)
cons = []
cons_lb = []
cons_ub = []
Expand Down
4 changes: 2 additions & 2 deletions do_mpc/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,7 @@ def set_default_objective(self, P_x, P_v=None, P_p=None, P_w=None):


# Calculate stage cost:
stage_cost = 0
stage_cost = DM(0)

if P_v is None:
assert n_v == 0, 'Must pass weighting factor P_v, since you have measurement noise on some measurements (configured in model).'
Expand Down Expand Up @@ -1220,7 +1220,7 @@ def _prepare_nlp(self):
self.ub_opt_x = opt_x(np.inf)

# Initialize objective function and constraints
obj = 0
obj = DM(0)
cons = []
cons_lb = []
cons_ub = []
Expand Down
22 changes: 20 additions & 2 deletions do_mpc/sampling/datahandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from do_mpc.tools import load_pickle, save_pickle
import types
import logging
from inspect import signature



Expand Down Expand Up @@ -149,7 +150,11 @@ def _post_process_single(self,sample,result):
if self.flags['set_post_processing']:
for key in self.post_processing:
if result is not None:
result_processed[key] = self.post_processing[key](result)
# post_processing function is either just a function of the result or of the sample and the result.
if self.post_processing[key]['n_args'] == 1:
result_processed[key] = self.post_processing[key]['function'](result)
elif self.post_processing[key]['n_args'] == 2:
result_processed[key] = self.post_processing[key]['function'](sample, result)
else:
result_processed[key] = None
# Result without post processing
Expand Down Expand Up @@ -283,6 +288,15 @@ def set_post_processing(self, name, post_processing_function):
The post processing function is applied to all loaded samples, e.g. with :py:meth:`__getitem__` or :py:meth:`filter`.
Users can set an arbitrary amount of post processing functions by repeatedly calling this method.
The ``post_processing_function`` can have two possible signatures:
1. ``post_processing_function(case_definition, sample_result)``
2. ``post_processing_function(sample_result)``
Where ``case_definition`` is a ``dict`` of all variables introduced in the :py:class:`do_mpc.sampling.samplingplanner.SamplingPlanner`
and ``sample_results`` is the result obtained from the function introduced with :py:class:`do_mpc.sampling.sampler.Sampler.set_sample_function`.
.. note::
Setting a post processing function with an already existing name will overwrite the previously set post processing function.
Expand Down Expand Up @@ -334,5 +348,9 @@ def sample_function(alpha, beta):
assert isinstance(name, str), 'name must be str, you have {}'.format(type(name))
assert isinstance(post_processing_function, (types.FunctionType, types.BuiltinFunctionType)), 'post_processing_function must be either Function or BuiltinFunction_or_Method, you have {}'.format(type(post_processing_function))

self.post_processing.update({name: post_processing_function})
# Check signature of function for number of arguments.
sig = signature(post_processing_function)
n_args = len(sig.parameters.keys())

self.post_processing.update({name: {'function': post_processing_function, 'n_args': n_args}})
self.flags['set_post_processing'] = True
2 changes: 1 addition & 1 deletion documentation/source/example_gallery/data_generator.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@
"id": "individual-official",
"metadata": {},
"source": [
"# Sampling closed-loop trajectories\n",
"## Sampling closed-loop trajectories\n",
"\n",
"A more reasonable use-case in the scope of **do-mpc** is to sample closed-loop trajectories of a dynamical system with a (MPC) controller. \n",
"\n",
Expand Down
21 changes: 18 additions & 3 deletions documentation/source/example_gallery/industrial_poly.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,6 @@
"mpc.bounds['lower','_x','accum_monom'] = 0.0\n",
"\n",
"# upper bound states\n",
"mpc.bounds['upper','_x','T_R'] = 363.15 + temp_range\n",
"mpc.bounds['upper','_x','T_S'] = 400.0\n",
"mpc.bounds['upper','_x','Tout_M'] = 400.0\n",
"mpc.bounds['upper','_x','T_EK'] = 400.0\n",
Expand All @@ -425,6 +424,22 @@
"mpc.bounds['upper','_x','T_adiab'] = 382.15"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The upper bound of the reactor temperature is set via a soft-constraint:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mpc.set_nl_cons('T_R_UB', _x['T_R'], ub=363.15+temp_range, soft_constraint=True, penalty_term_cons=1e4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -867,7 +882,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
Expand All @@ -881,7 +896,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
"version": "3.8.5"
},
"toc": {
"base_numbering": 1,
Expand Down
10 changes: 5 additions & 5 deletions documentation/source/getting_started.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1394,8 +1394,8 @@
"outputs": [],
"source": [
"# Change the color for the three states:\n",
"for line_i in mpc_graphics.pred_lines['_x', 'phi_1']: line_i.set_color('#1f77b4') # orange\n",
"for line_i in mpc_graphics.pred_lines['_x', 'phi_2']: line_i.set_color('#ff7f0e') # blue\n",
"for line_i in mpc_graphics.pred_lines['_x', 'phi_1']: line_i.set_color('#1f77b4') # blue\n",
"for line_i in mpc_graphics.pred_lines['_x', 'phi_2']: line_i.set_color('#ff7f0e') # orange\n",
"for line_i in mpc_graphics.pred_lines['_x', 'phi_3']: line_i.set_color('#2ca02c') # green\n",
"# Change the color for the two inputs: \n",
"for line_i in mpc_graphics.pred_lines['_u', 'phi_m_1_set']: line_i.set_color('#1f77b4')\n",
Expand Down Expand Up @@ -1869,9 +1869,9 @@
],
"metadata": {
"kernelspec": {
"display_name": "py36",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "py36"
"name": "python3"
},
"language_info": {
"codemirror_mode": {
Expand All @@ -1883,7 +1883,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.10"
"version": "3.8.5"
},
"toc": {
"base_numbering": 1,
Expand Down
8 changes: 7 additions & 1 deletion examples/industrial_poly/template_mpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ def template_mpc(model):
mpc.bounds['lower','_x','Tout_AWT'] = 288.0
mpc.bounds['lower','_x','accum_monom'] = 0.0

mpc.bounds['upper','_x','T_R'] = 363.15 + temp_range
mpc.bounds['upper','_x','T_S'] = 400.0
mpc.bounds['upper','_x','Tout_M'] = 400.0
mpc.bounds['upper','_x','T_EK'] = 400.0
Expand All @@ -95,6 +94,13 @@ def template_mpc(model):

mpc.scaling['_u','m_dot_f'] = 100

# Check if robust multi-stage is active
if mpc.n_robust == 0:
# Sot-constraint for the reactor upper bound temperature
mpc.set_nl_cons('T_R_UB', _x['T_R'], ub=363.15+temp_range, soft_constraint=True, penalty_term_cons=1e4)
else:
mpc.bounds['upper','_x','T_R'] = 363.15+temp_range


delH_R_var = np.array([950.0, 950.0 * 1.30, 950.0 * 0.70])
k_0_var = np.array([7.0*1.00, 7.0*1.30, 7.0*0.70])
Expand Down

0 comments on commit 1a44d39

Please sign in to comment.