yaocptool.modelling package

Submodules

yaocptool.modelling.dae_system module

class DAESystem(x=None, y=None, p=None, ode=None, alg=None, t=None, tau=None)[source]

Bases: object

DAE System class used primarily for simulation by the SystemModel class

For modelling it is recommended the use of the SystemModel class, use this class if you need more control of the integrator.

__init__(x=None, y=None, p=None, ode=None, alg=None, t=None, tau=None)[source]
DAE System class used primarily for simulation by the SystemModel class

For modelling it is recommended the use of the SystemModel class, use this class if you need more control of the integrator.

Parameters:
  • ode (casadi.SX) – ODE equations
  • alg (casadi.SX) – Algebraic equations
  • x (casadi.SX) – State variables
  • y (casadi.SX) – Algebraic variables
  • p (casadi.SX) – Parameters
  • t (casadi.SX) – Time variable
  • tau (casadi.SX) – Tau variable
convert_from_tau_to_time(t_k, t_kp1)[source]
Transform a dependence in tau into a dependence into t

Uses the formula tau_sym = (t - t_k)/ (t_kp1 - t_k)

Parameters:
  • t_k – t(k), the time at the beginning of the simulation interval
  • t_kp1 – t(k+1), the time at the end of the simulation interval
dae_system_dict
Return the dictionary of variables and equations needed to create the CasADi integrator.
Return type:dict
depends_on(var)[source]
Return True if the system of equations (‘ode’ and ‘alg’)depends on ‘var’ (contains ‘var’ in the equations).
Parameters:var (casadi.SX) –
Return type:bool
has_parameters
Return True if the attribute ‘p’ is not empty
Return type:bool
has_variable(var)[source]
Return True if the var is one of the system variables (x, y, p, t, tau)
Parameters:var (casadi.SX) –
Return type:bool
is_dae
Return True if it is a DAE system (with non empty algebraic equations)
Return type:bool
is_ode
Return True if it is a ODE system (no algebraic equations)
Return type:bool
join(dae_sys)[source]
Include all the variables and equations from the DAESystem ‘dae_sys’ into this object
Parameters:dae_sys (DAESystem) –
simulate(x_0, t_f, t_0=0.0, p=None, y_0=None, integrator_type='implicit', integrator_options=None)[source]
Create an integrator and simulate a system from ‘t_0’ to ‘t_f’.
Parameters:
  • x_0 (list|DM|MX) – initial condition
  • t_f (float|int|DM) – final time
  • t_0 (float|int|DM) – initial time
  • p (list|DM|MX) – system parameters
  • y_0 (list|DM|MX) – initial guess for the algebraic variable
  • integrator_type (str) – integrator type, options available are: ‘cvodes’, ‘idas’, ‘implicit’ (default, auto-select between ‘idas’ and ‘cvodes’), ‘rk’, and ‘collocation’.
  • integrator_options (dict) – casadi.integrator options
Return type:

dict

substitute_variable(old_var, new_var)[source]
Substitute ‘old_var’ with ‘new_var’ in the system equations (alg, ode) and in the set of variables (x, y, p)
Parameters:
  • old_var (casadi.SX) –
  • new_var (casadi.SX) –
type
Return ‘ode’ if the system has no algebraic equations, ‘dae’ otherwise
Return type:str

yaocptool.modelling.dataset module

class DataSet(name='dataset', **kwargs)[source]

Bases: object

__init__(name='dataset', **kwargs)[source]
Generic time dependent data storage. The data is stored in the self.data dictionary. self.data[‘entry_name’][‘time’] is a row vector self.data[‘entry_name’][‘values’] is a matrix with the same number of columns as the time vector, and rows equal to self.data[‘entry_name’][‘size’]. The data can be more easily managed using create_entry, get_entry, insert_data.
Parameters:
  • name (str) – name of th dataset
  • plot_style (str) – default plot style. plot = linear interpolation, step = piecewise constant (‘plot’ | ‘step’)
  • find_discontinuity (bool) – Default: True. If True, it will try to find discontinuity on the data, and plot with gaps where data is missing/not available, instead of a line connecting all data points.
  • max_sampling_time (float) – maximum expected distance between two time data. This is used to detect discontinuity on the data, and plot it separately.
create_entry(entry, size, names=None, plot_style=None)[source]
Create an entry in the dataset
Parameters:
  • entry – entry name
  • size – number of rows in the vector
  • names (list) – name for each row, it should be a list with size ‘size’. If ‘names’ is not given, then the name list [entry_1, entry_2, …, entry_size]
  • plot_style (str) – (‘plot’ | ‘step’) choose if the plot will be piecewise constant (step) or a first order interpolation (plot).
extend(other_dataset)[source]

Extend this DataSet with another DataSet. They don’t need to be ordered, after the merging a chronological sort of the data is performed.

Parameters:other_dataset (DataSet) –
Returns:
get_copy()[source]
Return a copy of this dataset. The copy is not connected to the original data set, therefore changes in one of the dataset will not affect the other.
Returns:
get_entry(entry)[source]
Return the time and values for a given entry.
Parameters:entry (str) – entry name
Returns:entry time, entry value
Return type:tuple
get_entry_names(entry)[source]
Get list of names of an entry
Parameters:entry
Return type:list
get_entry_size(entry)[source]
Get size of an entry
Parameters:entry
Returns:
insert_data(entry, time, value)[source]

Insert data on the dataset

Parameters:
  • entry (str) – entry name (‘x’, ‘y’, ‘u’, …)
  • time (float|list|DM) – time or time vector of the data
  • value (DM) – vector or matrix of values for the entry (column represent time)
plot(plot_list, figures=None, show=True, exact=False)[source]

Plot DataSet information. It takes as input a list of dictionaries, each dictionary represents a plot. In the dictionary use keyword ‘x’, ‘u’, ‘y’, etc., to specify which entry you want to print, the value of the dictionary should be a list of index, names, or regex expressions of the entries to be printed. Alternatively, instead of a list a string ‘all’ can be passed so all the elements of the entry are plotted.

Usage:
result.plot({‘x’:’all’, ‘y’:’all’, ‘u’:’all’}) # print all variables in a single plot result.plot([{‘x’:[0,3]}, {‘y’:’all’}, {‘u’:[‘v_1’, ‘q_out’]}]) # create 3 plots, with the selected vars result.plot(‘all’) # create 3 plots one with all ‘x’, one with all ‘y’, and one with all ‘u’
Parameters:
  • plot_list (list|str) – List of dictionaries to generate the plots.
  • figures (list) – list of figures to be plotted on top (optional)
  • show (bool) – if the plotted figures should be shown after plotting (optional, default=True).
  • exact (bool) – If true only precise match of entry elements will be plotted, otherwise a regex match will be used
save(file_path)[source]
Save this object in the “file_path” using pickle (.p extension). It can be retrieved using using pickle.load
Parameters:file_path (str) – path with file name of the file to be saved. Example: files/result.p
sort(entries=None)[source]
Sort the dataset for given ‘entries’ in an chronological order, this can be used when data is not inserted in an ordered fashion.
Parameters:entries (list) – list of entries to be sorted, if this parameter is no given all the entries will be sorted.

yaocptool.modelling.ocp module

Created on Mon Apr 03 11:15:03 2017

@author: marco

class OptimalControlProblem(model=None, name='OCP', x_0=None, t_0=0.0, t_f=1.0, **kwargs)[source]

Bases: object

Optimal Control Problem class, used to define a optimal control problem based on a model (SystemModel) It has the following form:

\[ \begin{align}\begin{aligned}\begin{split}\\min J &= V(x(t_f), p) + \int_{t_0} ^{t_f} L(x,y,u,t,p,\\theta) \, dt + \sum_{k} S(x(t_k), y(t_k), u(t_k), t_k, p, \\theta_k)\end{split}\\\begin{split}\\textrm{s.t.:}\,& \dot{x} = f(x,y,u,t,p,\\theta)\end{split}\\\begin{split}& g(x,y,u,t,p,\\theta) = 0\end{split}\\\begin{split}& g_{eq} (x,y,u,t,p,\\theta) = 0\end{split}\\\begin{split}& g_{ineq}(x,y,u,t,p,\\theta) \leq 0\end{split}\\& x_{min} \leq x \leq x_{max}\\& y_{min} \leq y \leq y_{max}\\& u_{min} \leq u \leq u_{max}\\& \Delta u_{min} \leq \Delta u \leq \Delta u_{max}\\\begin{split}& h_{initial} (x (t_0), t_0, p, \\theta) = 0\end{split}\\\begin{split}& h_{final} (x (t_f), t_f, p, \\theta) = 0\end{split}\\& h (p) = 0\end{aligned}\end{align} \]

where \(t_k\) is final time in each finite element.

__init__(model=None, name='OCP', x_0=None, t_0=0.0, t_f=1.0, **kwargs)[source]
Parameters:
  • model (yaocptool.modelling.SystemModel) –
  • name (str) –
  • x_0 (casadi.DM|list) – initial conditions
  • t_0 (float) –
  • t_f (float) –
  • kwargs
connect(u, y)[source]

Connect an input ‘u’ to a algebraic variable ‘y’, u = y. The function will perform the following actions: - include an algebraic equation u - y = 0 - remove ‘u’ from the input vector (since it is not a free variable anymore) - include ‘u’ into the algebraic vector, since it is an algebraic variable now. - move associated bounds (u_max, u_min) to (y_max, y_min), remove delta_u_max/delta_u_min

Parameters:
  • u – input variable
  • y – algebraic variable
create_adjoint_states()[source]
create_algebraic(name, size=1, alg=None, y_max=None, y_min=None, y_guess=None)[source]
create_control(name, size=1, u_min=None, u_max=None, delta_u_min=None, delta_u_max=None, u_guess=None)[source]
create_cost_state()[source]

Create and state with the dynamics equal to L from int_{t_0}^{t_f} L(…) dt: dot{x}_c = L(…)

Return type:casadi.SX
create_input
create_optimization_parameter(name, size=1, p_opt_min=None, p_opt_max=None)[source]
create_optimization_theta(name, size=1, new_theta_opt_min=None, new_theta_opt_max=None)[source]
create_parameter(name, size=1)[source]
create_quadratic_cost(par_dict)[source]
create_state(name, size=1, ode=None, x_0=None, x_max=None, x_min=None, h_initial=None)[source]
create_theta(name, size=1)[source]
get_p_opt_indices()[source]
get_theta_opt_indices()[source]
has_delta_u
include_algebraic(var, alg=None, y_min=None, y_max=None, y_guess=None)[source]
include_control(var, u_min=None, u_max=None, delta_u_min=None, delta_u_max=None, u_guess=None)[source]
include_equality(eq)[source]

Include time independent equality. Equality is concatenated “h”.

Parameters:eq – time independent equality
include_final_time_equality(eq)[source]

Include final time equality. Equality that is evaluated at t=t_f. The equality is concatenated to “h_final”

Parameters:eq – final equality constraint
include_initial_time_equality(eq)[source]

Include initial time equality. Equality that is evaluated at t=t_0. The equality is concatenated to “h_initial”

Parameters:eq – initial equality constraint
include_optimization_parameter(var, p_opt_min=None, p_opt_max=None)[source]
include_optimization_theta(var, theta_opt_min=None, theta_opt_max=None)[source]
include_parameter(p)[source]
include_state(var, ode=None, x_0=None, x_min=None, x_max=None, h_initial=None, x_0_sym=None, suppress=False)[source]
include_system_equations(ode=None, alg=None)[source]
include_theta(theta)[source]
include_time_equality(eq, when='default')[source]

Include time dependent equality. g_eq(…, t) = 0, for t in [t_0, t_f]

The inequality is concatenated to “g_ineq”

Parameters:
  • eq – equality
  • when (str) – Can be ‘default’, ‘end’, ‘start’. ‘start’ - the constraint will be evaluated at the start of every finite element ‘end’ - the constraint will be evaluated at the end of every finite element ‘default’ - will be evaluated at each collocation point of every finite element. For the multiple shooting, the constraint will be evaluated at the end of each finite element
include_time_inequality(eq, when='default')[source]

Include time dependent inequality. g_ineq(…, t) <= 0, for t in [t_0, t_f]

The inequality is concatenated to “g_ineq”

Parameters:
  • when (str) – Can be ‘default’, ‘end’, ‘start’. ‘start’ - the constraint will be evaluated at the start of every finite element ‘end’ - the constraint will be evaluated at the end of every finite element ‘default’ - will be evaluated at each collocation point of every finite element. For the multiple shooting, the constraint will be evaluated at the end of each finite element
  • eq – inequality
merge(problems)[source]
Parameters:of OptimalControlProblem problems (list) –
n_eta
n_g_eq
n_g_ineq
n_h_final
n_h_initial
n_p_opt
n_theta_opt
parametrize_control(u, expr, u_par=None)[source]
Parametrize the control variable
Parameters:
  • u
  • expr
  • u_par
pre_solve_check()[source]
remove_algebraic(var, eq=None)[source]
remove_control(var)[source]
replace_variable(original, replacement)[source]
Replace ‘original’ by ‘replacement’ in the problem and model equations
Parameters:
  • original
  • replacement
reset_working_model()[source]
set_parameter_as_optimization_parameter(new_p_opt, new_p_opt_min=None, new_p_opt_max=None)[source]
set_theta_as_optimization_theta(new_theta_opt, new_theta_opt_min=None, new_theta_opt_max=None)[source]

yaocptool.modelling.simulation_result module

class SimulationResult(n_x, n_y, n_u, x_names=None, y_names=None, u_names=None, **kwargs)[source]

Bases: yaocptool.modelling.dataset.DataSet

__init__(n_x, n_y, n_u, x_names=None, y_names=None, u_names=None, **kwargs)[source]
Generic time dependent data storage.
The data is stored in the self.data dictionary. self.data[‘entry_name’][‘time’] is a row vector self.data[‘entry_name’][‘values’] is a matrix with the same number of columns as the time vector, and rows equal to self.data[‘entry_name’][‘size’]. The data can be more easily managed using create_entry, get_entry, insert_data.
Parameters:
  • name (str) – name of th dataset
  • plot_style (str) – default plot style. plot = linear interpolation, step = piecewise constant (‘plot’ | ‘step’)
  • find_discontinuity (bool) – Default: True. If True, it will try to find discontinuity on the data, and plot with gaps where data is missing/not available, instead of a line connecting all data points.
  • max_sampling_time (float) – maximum expected distance between two time data. This is used to detect discontinuity on the data, and plot it separately.
extend(other_sim_result)[source]

Extend this SimulationResult with other SimulationResult. It is only implemented for the case where the other simulation result starts at the end of this simulation. That is this.t_f == other_sim_result.t_0 .

Parameters:other_sim_result (SimulationResult) –
Returns:
final_condition()[source]

Return the simulation final condition in the form of a tuple (x_f, y_f, u_f)

Return type:DM, DM, DM
n_u
n_x
n_y
t
u
u_names
x
x_names
y
y_names

yaocptool.modelling.stochastic_ocp module

class StochasticOCP(model, **kwargs)[source]

Bases: yaocptool.modelling.ocp.OptimalControlProblem

__init__(model, **kwargs)[source]
Parameters:
  • model (yaocptool.modelling.SystemModel) –
  • name (str) –
  • x_0 (casadi.DM|list) – initial conditions
  • t_0 (float) –
  • t_f (float) –
  • kwargs
create_uncertain_parameter(name, mean, var, size=1, distribution='normal')[source]
get_p_unc_indices()[source]
get_p_without_p_unc()[source]
get_uncertain_initial_cond_indices()[source]
include_time_chance_inequality(ineq, prob, rhs=None, when='default')[source]

Include time dependent chance inequality. Prob[ineq(…, t) <= rhs] <= prob, for t in [t_0, t_f]

The inequality is concatenated to “g_stochastic_ineq”

Parameters:
  • ineq – inequality
  • rhs (list|DM) – Right-hand size of the inequality
  • prob (list|DM) – Chance/probability of the constraint being satisfied
  • when (str) – Can be ‘default’, ‘end’, ‘start’. ‘start’ - the constraint will be evaluated at the start of every finite element ‘end’ - the constraint will be evaluated at the end of every finite element ‘default’ - will be evaluated at each collocation point of every finite element. For the multiple shooting, the constraint will be evaluated at the end of each finite element
include_uncertain_parameter(par, mean, cov, distribution='normal')[source]
n_g_stochastic
n_p_unc
n_uncertain_initial_condition
set_initial_condition_as_uncertain(par, mean, cov, distribution='normal')[source]
set_parameter_as_uncertain_parameter(par, mean, cov, distribution='normal')[source]

yaocptool.modelling.system_model module

Created on Thu Jun 09 10:50:48 2016

@author: marco

class SystemModel(name='model', model_name_as_prefix=False, **kwargs)[source]

Bases: yaocptool.modelling.mixins.state_mixin.StateMixin, yaocptool.modelling.mixins.algebraic_mixin.AlgebraicMixin, yaocptool.modelling.mixins.control_mixin.ControlMixin, yaocptool.modelling.mixins.parameter_mixin.ParameterMixin

__init__(name='model', model_name_as_prefix=False, **kwargs)[source]
Continuous-time Dynamic System Model
\[\begin{split}\dot{x} = f(x,y,u,t,p,\\theta) \\\\ g(x,y,u,t,p,\\theta) = 0\\\\\end{split}\]

x - states y - algebraic u - control p - constant parameters theta - parameters dependent of the finite_elements (e.g.: disturbances)

Note: when vectorizing the parameters order is [ p; theta; u_par]

Parameters:
  • name – model name
  • model_name_as_prefix (bool) – if true all variables create will have the model name as prefix e.g.: ‘tank_h’, where ‘tank’ is model name and ‘h’ is the state created
all_sym
static all_sym_names()[source]
connect(u, y)[source]

Connect an input ‘u’ to a algebraic variable ‘y’, u = y. The function will perform the following actions: - include an algebraic equation u - y = 0 - remove ‘u’ from the input vector (since it is not a free variable anymore) - include ‘u’ into the algebraic vector, since it is an algebraic variable now.

Parameters:
  • u – input variable
  • y – algebraic variable
convert_expr_from_tau_to_time(expr, t_k, t_kp1)[source]
convert_expr_from_time_to_tau(expr, t_k, t_kp1)[source]
find_equilibrium(additional_eqs, guess=None, t_0=0.0, rootfinder_options=None)[source]

Find a equilibrium point for the model. This method solves the root finding problem:

f(x,y,u,t_0) = 0 g(x,y,u,t_0) = 0 additional_eqs (x,y,u,t_0) = 0

Use additional_eqs to specify the additional conditions remembering that dim(additional_eqs) = n_u, so the system can be well defined. If no initial guess is provided (“guess” parameter) a guess of ones will be used (not zero to avoid problems with singularities.

Returns x_0, y_0, u_0

Parameters:
  • rootfinder_options (dict) – options to be passed to rootfinder
  • additional_eqs – SX
  • guess – DM
  • t_0 – float
Returns:

(DM, DM, DM)

get_copy()[source]
Get a copy of this model.

Uses copy.copy to get copy of this object.

Return type:SystemModel
get_dae_system()[source]

Return a DAESystem object with the model equations.

Returns:DAESystem
get_deepcopy()[source]
Get a deep copy of this model, differently from “get_copy”, the variables of the original copy and the hard copy will not be the same, i.e. model.x != copy.x
Return type:SystemModel
get_variable_by_name(name='', var_type=None)[source]
Return a variable with a specified name (Regex accepted).

If no or multiple variables are found with the specified ‘name’ an ValueError exception is raised. To specify the search in a single variable type (x/y/u/p/theta) use the ‘var_type’

Parameters:
  • name (str) – variable name/regex
  • var_type (str) – variable type (optional)
Returns:

variable

Return type:

SX

get_variables_by_names(names='', var_type=None)[source]
Parameters:
  • of str names (str|list) – list of variables names
  • var_type (str) –
has_variable(var)[source]
Parameters:var (casadi.SX) – variable to be checked if it is in the SystemModel
include_equations(*args, **kwargs)[source]
Include model equations, (ordinary) differential equation and algebraic equation (ode and alg)
Parameters:
  • ode (list|casadi.SX) – (ordinary) differential equation
  • alg (list|casadi.SX) – algebraic equation
include_models(models)[source]
Include model or list of models into this model. All the variables and functions will be included.
Parameters:models (list|SystemModel) – models to be included
include_variables(x=None, y=None, u=None, p=None, theta=None)[source]
Include variables (x, y, u, p, and theta) to the model.
Parameters:
  • x (SX|list|None) – state variable
  • y (SX|list|None) – algebraic variable
  • u (SX|list|None) – control/input variable
  • p (SX|list|None) – parameter variable
  • theta (SX|list|None) – element dependent variable
is_parametrized()[source]
Check if the model is parametrized.
Rtype bool:
lamb_sym
linearize(x_bar, u_bar)[source]

Returns a linearized model at a given points (X_BAR, U_BAR)

merge(models_list, connecting_equations=None)[source]
print_summary()[source]

Print model summary when using print(model)

Returns:
print_variables()[source]

Print list of variable in the model (x, y, u, p, theta)

static put_values_in_all_sym_format(t=None, x=None, y=None, p=None, theta=None, u_par=None)[source]
replace_variable(original, replacement)[source]

Replace a variable or parameter by an variable or expression.

Parameters:
  • replacement (SX|list) –
  • original (SX|list) – and replacement, and also variable type which describes which type of variable is being remove to it from the counters. Types: ‘x’, ‘y’, ‘u’, ‘p’, ‘ignore’
simulate(x_0, t_f, t_0=0.0, u=None, p=None, theta=None, y_0=None, integrator_type='implicit', integrator_options=None)[source]
Simulate model.
If t_f is a float, then only one simulation will be done. If t_f is a list of times, then a sequence of simulations will be done, that each t_f is the end of a finite element.
Parameters:
  • x_0 (list||DM) – Initial condition
  • t_f (float||list) – Final time of the simulation, can be a list of final times for sequential simulation
  • t_0 (float) – Initial time
  • u (list||DM) – Controls of the system to be simulated
  • p (DM||SX||list) – Simulation parameters
  • theta (dict) – Parameters theta, which varies for each simulation for sequential simulations. If t_f is a list then theta has to have one entry for each k in [0,…,len(t_f)]
  • y_0 – Initial guess for the algebraic variables
  • integrator_type (str) – ‘implicit’ or ‘explicit’
  • integrator_options (dict) – options to be passed to the integrator
Return type:

SimulationResult

system_type
Return the system type.
Returns:‘ode’ if an ODE system and ‘dae’ if an DAE system
Return type:str
t = SX(t)
t_sym
tau = SX(tau)
tau_sym
x_sys_sym

yaocptool.modelling.utils module

class Derivative(inner)[source]

Bases: object

__init__(inner)[source]

Initialize self. See help(type(self)) for accurate signature.

class EqualityEquation(lhs, rhs)[source]

Bases: object

__init__(lhs, rhs)[source]

Initialize self. See help(type(self)) for accurate signature.

der(*args, **kwargs)[source]

Module contents

Created on Mon Jul 10 14:27:21 2017

@author: marco