Commit a53444ca authored by Patrick Rüdiger's avatar Patrick Rüdiger
Browse files

improved automatic plot generation in mpc.py, adjusted calculation of ef in opc.py (not final)

parent 7e03f5af
......@@ -121,7 +121,7 @@ def create_solver():
'receding': 'global',
'u_guess': None,
'x_guess': None,
'verbosity': 0}
'verbosity': 5}
# Create MPCSolver object. See constructor docstring for details.
solver = mpci.MPCSolver(ocp, **kwargs)
......@@ -129,61 +129,6 @@ def create_solver():
return solver
def print_results():
name = sys.info_dict['name'] + '_' + ocp.mode + '_' + solver.receding
print('{:<30} {:<10} {:<10}'.format('', 'J_f', 'e_f'))
print('{:<30} {:<10.1f} {:<10.1e}'.format(name, sol['J_f'], sol['e_f']))
def plot_results():
to_plot = [[['x_0'], ['x_1'], ['u_0']]]
fig_size = [30/2.54, 20/2.54]
font_size = 20
fig_name = sys.info_dict['name'] + '_' + ocp.mode + '_' + solver.receding
show = True
tud_blue = '#00305d'
colors = [[[tud_blue], [tud_blue], [tud_blue]]]
drawstyles = [[['default'], ['default'], ['steps-post']]]
linewidths = [[[2], [2], [2]]]
x_min = -0.03
x_max = 1.53
x_ticks = [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5]
labels = {'t': r'$t$ in s $\rightarrow$',
'x_0': r'$\uparrow$' + '\n' + r'$x_0$ in m',
'x_1': r'$\uparrow$' + '\n' + r'$x_1$ in '
+ r'$\mathrm{\frac{m}{s}}$',
'u_0': r'$\uparrow$' + '\n' + r'$u$ in '
+ r'$\mathrm{\frac{m}{s^2}}$'}
x_array = sol['tgrid_sim']
x_label = labels['t']
y_arrays = []
y_labels = []
for i in range(len(to_plot)):
pltr = mpci.Plotter(x_label, x_array)
y_arrays.append([])
for k in range(len(to_plot[i])):
y_arrays[i].append([])
y_labels.append('')
for j in range(len(to_plot[i][k])):
key = to_plot[i][k][j]
if 'x' in key:
y_arrays[i][k].append(sol['x_sim'][:, int(key[-1])])
elif 'u' in key:
y_arrays[i][k].append(sol['u_sim'][:, int(key[-1])])
y_labels[-1] += key
y_labels[-1] = labels[y_labels[-1]]
pltr.add_subplot(y_arrays[i][k], y_labels[-1], colors=colors[i][k],
drawstyles=drawstyles[i][k],
linewidths=linewidths[i][k])
pltr.create_plot(fig_size, fig_name, font_size=font_size, show=show,
x_min=x_min, x_max=x_max, x_ticks=x_ticks, y_lpad=30)
if __name__ == '__main__':
# Create system, optimal control problem (ocp) and solver.
sys = create_system()
......@@ -193,7 +138,3 @@ if __name__ == '__main__':
# Solve the ocp in the specified manner. See docstring of solve() function
# for details. Solution (sol) will be cached to "sols/sol_cache.dat".
sol = solver.solve()
# Show results.
print_results()
plot_results()
......@@ -9,6 +9,8 @@ from joblib import dump as joblib_dump
from joblib import load as joblib_load
from joblib import hash as joblib_hash
from ..utils.plotter import Plotter
__all__ = ['optimize_QR', 'MPCSolver']
......@@ -346,37 +348,81 @@ class MPCSolver(object):
def _plot(self):
plt.close('all')
plt.rcdefaults()
plt.figure('x_sim and u_sim')
legend = []
for i in range(self.ocp_sim.sys.n_x):
plt.plot(self.sol['tgrid_sim'], self.sol['x_sim'][:, i], '-')
legend.append('x_'+str(i))
for i in range(self.ocp_sim.sys.n_u):
plt.plot(self.sol['tgrid_sim'][:-1], self.sol['u_sim'][:, i], '-',
drawstyle='steps-post', linewidth=1.0)
legend.append('u_'+str(i))
plt.xlabel('t')
plt.legend(legend)
plt.grid()
plt.show()
plt.figure('L_sim')
plt.plot(self.sol['tgrid_sim'][:-1], self.sol['L_sim'], '-')
plt.legend('L')
plt.xlabel('t')
plt.grid()
plt.show()
if self.ocp.mode == 'free':
plt.figure('alpha_a_sim and alpha_b_sim')
plt.plot(self.sol['tgrid_sim'][:len(self.sol['alpha_a_sim'])],
self.sol['alpha_a_sim'], '-')
plt.plot(self.sol['tgrid_sim'][:len(self.sol['alpha_b_sim'])],
self.sol['alpha_b_sim'], '-')
plt.xlabel('t')
plt.legend(['alpha_a_sim', 'alpha_b_sim'])
plt.grid()
plt.show()
to_plot = []
to_plot_fig = []
var_list = ['x', 'u']
var_list_new = []
for var in var_list:
for idx in range(getattr(self.ocp_sim.sys, 'n_' + var)):
var_list_new.append(var + '_' + str(idx))
to_plot_fig.append([var_list_new[-1]])
if (idx + 1) % 3 == 0:
to_plot.append(to_plot_fig)
to_plot_fig = []
if len(to_plot_fig) > 0:
to_plot.append(to_plot_fig)
to_plot_fig = []
var_list = var_list_new
to_plot.append([['L_sim']])
var_list.append('L_sim')
if self.ocp.mode == 'free' and self.estimate_alphas:
to_plot.append([['alpha_a_sim', 'alpha_b_sim']])
var_list.extend(['alpha_a_sim', 'alpha_b_sim'])
fig_size = [30/2.54, 20/2.54]
font_size = 18
fig_base_name = (self.ocp.sys.info_dict['name'] + '_' + self.ocp.mode
+ '_' + self.receding + '_')
tud_blue = '#00305d'
drawstyles = {}
for var in var_list:
if 'u' in var:
drawstyles[var] = 'steps-post'
else:
drawstyles[var] = 'default'
linewidths = 2
alpha_a_str = r'$\hat{\alpha}_\mathrm{ES},'
alpha_b_str = r'\hat{\alpha}_\mathrm{ZS}$'
y_str_1 = r'$\uparrow$' + '\n'
labels = {'t': r'$t$ $\rightarrow$',
'L_sim': y_str_1 + r'$l(\mathbf{x}, \mathbf{u})$',
'alpha_a_simalpha_b_sim': y_str_1+alpha_a_str+alpha_b_str}
x_array = self.sol['tgrid_sim']
x_label = labels['t']
y_arrays = []
y_labels = []
for i in range(len(to_plot)):
pltr = Plotter(x_label, x_array)
y_arrays.append([])
for k in range(len(to_plot[i])):
y_arrays[i].append([])
y_labels.append('')
for j in range(len(to_plot[i][k])):
key = to_plot[i][k][j]
if 'x' in key:
y_arrays[i][k].append(
self.sol['x_sim'][:, int(key[2:])])
elif 'u' in key:
y_arrays[i][k].append(
self.sol['u_sim'][:, int(key[2:])])
else:
y_arrays[i][k].append(self.sol[key])
y_labels[-1] += key
if 'x' in key or 'u' in key:
y_labels[-1] = (y_str_1 + r'$' + key[:2] + '{' + key[2:]
+ r'}$')
else:
y_labels[-1] = labels[y_labels[-1]]
pltr.add_subplot(y_arrays[i][k], y_labels[-1], colors=tud_blue,
drawstyles=drawstyles[key],
linewidths=linewidths)
pltr.create_plot(fig_size, fig_base_name + str(i),
font_size=font_size, show=True, y_lpad=30)
def _estimate_alphas(self):
L_inf_0 = self.ocp.L_fun(self.x_opts[-1][0, :], self.ocp.u_ref[0],
......
......@@ -177,7 +177,11 @@ class OptimalControlProblem(object):
if self.mode == 'xN':
if 'e_x_tol' in self.data.keys():
self.ef = e_x**2 - self.data['e_x_tol']**2
ef = ca.fmax(e_x**2 - self.data['e_x_tol']**2,
np.zeros(self.sys.n_x))
# TODO: skalares oder vektorielles ef zu bevorzugen?
# self.ef = ef.T @ ef
self.ef = ef
else:
self.ef = e_x.T @ e_x
self.ef_fun = ca.Function('ef_fun', [self.sys.x, self.x_sp],
......
......@@ -5,6 +5,7 @@ import locale
import numpy as np
from matplotlib import colors
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
__all__ = ['Plotter']
......@@ -148,6 +149,10 @@ class Plotter(object):
plt.xlim(left=x_min)
if x_max is not None:
plt.xlim(right=x_max)
axs[i].xaxis.set_major_formatter(FuncFormatter(
lambda v, _: '{:.3e}'.format(v).replace('.', ',')))
axs[i].yaxis.set_major_formatter(FuncFormatter(
lambda v, _: '{:.3e}'.format(v).replace('.', ',')))
if x_ticks is not None:
plt.xticks(ticks=x_ticks, labels=x_tick_labels)
plt.setp(axs[i].get_xticklabels(),
......
......@@ -12,7 +12,7 @@ with open(os.path.join(cdir, 'requirements.txt'), 'r', encoding='utf-8') as fh:
setuptools.setup(
name='mpctools_interface',
version='0.0.3',
version='0.0.4',
author='Patrick Rüdiger',
author_email='patrick.ruediger@tu-dresden.de',
description='mpc-tools-casadi-interface',
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment