API¶
direct_collocation.py¶
- class opty.direct_collocation.ConstraintCollocator(
- equations_of_motion,
- state_symbols,
- num_collocation_nodes,
- node_time_interval,
- known_parameter_map={},
- known_trajectory_map={},
- instance_constraints=None,
- time_symbol=None,
- tmp_dir=None,
- integration_method='backward euler',
- parallel=False,
- show_compile_output=False,
- backend='cython',
This class is responsible for generating the constraint function and the sparse Jacobian of the constraint function using direct collocation methods for a non-linear programming problem where the essential constraints are defined from the equations of motion of the system.
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of states
m : number of input trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals (0 or 1 if fixed duration or variable duration)
o : number of instance constraints
nN + qN + r + s : number of free variables
M(N - 1) + o : number of constraints
Some of the attributes are explained in more detail under Parameters below.
It is best to treat
ConstraintCollocatoras immutable, changing attributes after initialization will inevitably fail.Instantiates a ConstraintCollocator object.
- Parameters:
equations_of_motion (sympy.Matrix, shape(M, 1)) – A column matrix of SymPy expressions defining the right hand side of the equations of motion when the left hand side is zero, i.e.
0 = f(x'(t), x(t), u(t), p). These should be in first order form but not necessairly explicit. They can be ordinary differential equations or differential algebraic equations.state_symbols (iterable) – An iterable containing all
nof the SymPy functions of time which represent the states in the equations of motion.num_collocation_nodes (integer) – The number of collocation nodes,
N. All known trajectory arrays should be of this length.node_time_interval (float or Symbol) – The time interval between collocation nodes. If a SymPy symbol is provided, the time interval will be treated as a free variable resulting in a variable duration solution.
known_parameter_map (dictionary, optional) – A dictionary that maps the SymPy symbols representing the known constant parameters to floats. Any parameters in the equations of motion not provided in this dictionary will become free optimization variables.
known_trajectory_map (dictionary, optional) – A dictionary that maps the non-state SymPy functions of time and possibly their derivatives to ndarrays of floats of
shape(N,)or functions that generate ndarrays of floats given the free optimization vector as an input. Any time varying parameters in the equations of motion not provided in this dictionary will become free trajectories optimization variables. If solving a variable duration problem, note that the values here are fixed at each node and will not scale with a varying time interval. In that case, use numerical functions to produce the known arrays.instance_constraints (iterable of SymPy expressions, optional) – These expressions are for constraints on the states at specific times. They can be expressions with any state instance and any of the known parameters found in the equations of motion. All states should be evaluated at a specific instant of time. For example, the constraint
x(0) = 5.0would be specified asx(0) - 5.0. For variable duration problems you must specify time as an integer multiple of the node time interval symbol, for examplex(0*h) - 5.0. The integer must be a value from 0 tonum_collocation_nodes - 1. Unknown parameters and time varying parameters other than the states are currently not supported.time_symbol (SymPy Symbol, optional) – The symbol representating time in the equations of motion. If not given, it is assumed to be the default stored in
sympy.physics.vector.dynamicsymbols._t.tmp_dir (string, optional) – If you want to see the generated Cython and C code for the constraint and constraint Jacobian evaluations, pass in a path to a directory here. Additionally, if this temporary directory is set to an existing populated directory and the equations of motion have not changed relative to prior instantiations of this class, the compilation step will be skipped if equivalent compiled modules are already present and cached. This may save significant computational time when repeatedly using the same set of equations of motion.
integration_method (string, optional) – The integration method to use, either
backward eulerormidpoint.parallel (boolean, optional) – If true and openmp is installed, constraints and the Jacobian of the constraints will be executed across multiple threads. This is only useful for performance when the equations of motion have an extremely large number of operations. Only available with the
'cython'backend.show_compile_output (boolean, optional) – If True, STDOUT and STDERR of the Cython compilation call will be shown. Only available with the
'cython'backend.backend (string, optional) – Backend used to generate the numerical functions, either
'cython'(default) or'numpy'.
- property current_discrete_specified_symbols¶
The symbols for the current discrete specified inputs. Type: tuple
- property current_discrete_state_symbols¶
The symbols for the current discrete states. Type: n-tuple
- property current_known_discrete_specified_symbols¶
The symbols for the current discrete specified inputs. Type: tuple
- property current_unknown_discrete_specified_symbols¶
The symbols for the current unknown discrete specified inputs. Type: tuple
- property discrete_eom¶
Discretized equations of motion. Depending on the integration method used. Type: sympy.Matrix, shape(M, 1)
- property eom¶
The equations of motion used. Type: sympy.Matrix, shape(M, 1)
- generate_constraint_function()[source]¶
Returns a function which evaluates the constraints given the array of free optimization variables.
- generate_jacobian_function()[source]¶
Returns a function which evaluates the Jacobian of the constraints given the array of free optimization variables.
- property input_trajectories¶
known_input_trajectories + unknown_input_trajectories. Type: tuple
- property instance_constraints¶
The instance constraints used in the optimization. Type: o-tuple
- property integration_method¶
The integration method used. Presently,
backward eulerandmidpointare supported. Type: str
- jacobian_indices()[source]¶
Returns the row and column indices for the non-zero values in the constraint Jacobian.
- Returns:
jac_row_idxs (ndarray, shape(2*n + q + r + s,)) – The row indices for the non-zero values in the Jacobian.
jac_col_idxs (ndarray, shape(M + o,)) – The column indices for the non-zero values in the Jacobian.
- property known_input_trajectories¶
The known input trajectories symbols. Type: tuple
- property known_parameter_map¶
A mapping of known parameters to their values. Type: dict
- property known_parameters¶
The symbols of the known parameters in the problem. Type: tuple
- property known_trajectory_map¶
A mapping of known trajectories to their values. Type: dict
- property next_discrete_specified_symbols¶
The symbols for the next discrete specified inputs. Type: tuple
- property next_discrete_state_symbols¶
The symbols for the next discrete states. Type: n-tuple
- property next_known_discrete_specified_symbols¶
The symbols for the next discrete specified inputs. Type: tuple
- property next_unknown_discrete_specified_symbols¶
The symbols for the next unknown discrete specified inputs. Type: tuple
- property node_time_interval¶
The time interval between collocation nodes. float if the interval is fixed,
sympy.Symbolif the interval is variable. Type: float or sympy.Symbol
- property num_collocation_nodes¶
Number of times spaced evenly between the initial and final time of the optimization Type: int
- property num_constraints¶
The number of constraints = (num_collection_nodes-1)*num_states + len(instance_constraints). Type: int
- property num_eom¶
Number of equations in the equations of motion. Type: int
- property num_free¶
Number of variables to be optimized = n*N + q*N + r + s. Type: int
- property num_input_trajectories¶
The number of input trajectories = len(input_trajectories). Type: int
- property num_instance_constraints¶
The number of instance constraints = len(instance_constraints). Type: int
- property num_known_input_trajectories¶
The number of known trajectories = len(known_input_trajectories). Type: int
- property num_known_parameters¶
The number of known parameters = len(known_parameters). Type: int
- property num_parameters¶
The number of parameters = len(parameters). Type: int
- property num_states¶
The number of states = len(state_symbols) = n. Type: int
- property num_unknown_input_trajectories¶
The number of unknown input trajectories = len(unknown_input_trajectories). Type: int
- property num_unknown_parameters¶
The number of unknown parameters = r. Type: int
- property parallel¶
Whether to use parallel processing or not. Type: bool
- property parameters¶
known_parameters + unknown_parameters. Type: tuple
- property previous_discrete_state_symbols¶
The symbols for the previous discrete states. Type: n-tuple
- property show_compile_output¶
Whether to show the compile output or not. Type: bool
- property state_derivative_symbols¶
symbols for the time derivatives of the states. Type: n-tuple
- property state_symbols¶
The symbols for the states. Type: n-tuple
- property time_interval_symbol¶
sympy.Symbol if the time interval is variable, float if the time interval is fixed. Type: sympy.Symbol or float
- property time_symbol¶
The symbol used to represent time, usually t. Type: sympy.Symbol
- property tmp_dir¶
The temporary directory used to store files generated. Type: str
- property unknown_input_trajectories¶
The unknown input trajectories symbols. Type: q-tuple
- property unknown_parameters¶
The unknown parameters in the problem, in the sequence in which they appear in the solution of the optimization. Type: r-tuple
- class opty.direct_collocation.Problem(
- obj,
- obj_grad,
- equations_of_motion,
- state_symbols,
- num_collocation_nodes,
- node_time_interval,
- known_parameter_map={},
- known_trajectory_map={},
- instance_constraints=None,
- time_symbol=None,
- tmp_dir=None,
- integration_method='backward euler',
- parallel=False,
- bounds=None,
- show_compile_output=False,
- backend='cython',
- eom_bounds=None,
This class allows the user to instantiate a problem object with the essential data required to solve a direct collocation optimal control or parameter identification problem.
This is a subclass of cyipopt’s Problem class.
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of states
m : number of input trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals (0 or 1 if fixed duration or variable duration)
o : number of instance constraints
nN + qN + r + s : number of free variables
M(N - 1) + o : number of constraints
If
xare the state variables,uare the unknown input trajectories, andpare the unknown parameters, andhis the unknown time interval then the free optimization variables are in this order:free = [x11, ... x1N, xn1, ... xnN, u11, ... u1N, uq1, ... xqN, p1, ... pr, h]
If the equations of motion are equations
eom1toeomMand instance constraints arec, the constraint array is ordered as:constraints = [eom12, ... eom1N, eomM2, ... eomMN, c1, ..., co]
- Parameters:
obj (function) – Returns the value of the objective function given the free vector. The call signature can be
obj(free)orobj(self, free)whereselfis the problem instance andfreeis an array.obj_grad (function) – Returns the gradient of the objective function given the free vector. The call signature can be
obj_grad(free)orobj_grad(self, free)whereselfis the problem instance andfreeis an array.equations_of_motion (sympy.Matrix, shape(M, 1)) – A column matrix of SymPy expressions defining the right hand side of the equations of motion when the left hand side is zero, i.e.
0 = f(x'(t), x(t), u(t), p). These should be in first order form but not necessairly explicit. They can be ordinary differential equations or differential algebraic equations.state_symbols (iterable) – An iterable containing all
nof the SymPy functions of time which represent the states in the equations of motion.num_collocation_nodes (integer) – The number of collocation nodes,
N. All known trajectory arrays should be of this length.node_time_interval (float or Symbol) – The time interval between collocation nodes. If a SymPy symbol is provided, the time interval will be treated as a free variable resulting in a variable duration solution.
known_parameter_map (dictionary, optional) – A dictionary that maps the SymPy symbols representing the known constant parameters to floats. Any parameters in the equations of motion not provided in this dictionary will become free optimization variables.
known_trajectory_map (dictionary, optional) – A dictionary that maps the non-state SymPy functions of time and possibly their derivatives to ndarrays of floats of
shape(N,)or functions that generate ndarrays of floats given the free optimization vector as an input. Any time varying parameters in the equations of motion not provided in this dictionary will become free trajectories optimization variables. If solving a variable duration problem, note that the values here are fixed at each node and will not scale with a varying time interval. In that case, use numerical functions to produce the known arrays.instance_constraints (iterable of SymPy expressions, optional) – These expressions are for constraints on the states at specific times. They can be expressions with any state instance and any of the known parameters found in the equations of motion. All states should be evaluated at a specific instant of time. For example, the constraint
x(0) = 5.0would be specified asx(0) - 5.0. For variable duration problems you must specify time as an integer multiple of the node time interval symbol, for examplex(0*h) - 5.0. The integer must be a value from 0 tonum_collocation_nodes - 1. Unknown parameters and time varying parameters other than the states are currently not supported.time_symbol (SymPy Symbol, optional) – The symbol representating time in the equations of motion. If not given, it is assumed to be the default stored in
sympy.physics.vector.dynamicsymbols._t.tmp_dir (string, optional) – If you want to see the generated Cython and C code for the constraint and constraint Jacobian evaluations, pass in a path to a directory here. Additionally, if this temporary directory is set to an existing populated directory and the equations of motion have not changed relative to prior instantiations of this class, the compilation step will be skipped if equivalent compiled modules are already present and cached. This may save significant computational time when repeatedly using the same set of equations of motion.
integration_method (string, optional) – The integration method to use, either
backward eulerormidpoint.parallel (boolean, optional) – If true and openmp is installed, constraints and the Jacobian of the constraints will be executed across multiple threads. This is only useful for performance when the equations of motion have an extremely large number of operations. Only available with the
'cython'backend.show_compile_output (boolean, optional) – If True, STDOUT and STDERR of the Cython compilation call will be shown. Only available with the
'cython'backend.backend (string, optional) – Backend used to generate the numerical functions, either
'cython'(default) or'numpy'.bounds (dictionary, optional) – This dictionary should contain a mapping from any of the symbolic states, unknown trajectories, unknown parameters, or unknown time interval to a 2-tuple of floats. If setting states or unknown trajectories, an ndarray of shape(N,) can be supplied instead of a float. The first entry of the 2-tuple is the lower bound and the second the upper bound for that free variable, e.g.
{x(t): (-1.0, 5.0)}or{x(t): (-1.0, np.ones(N))}.eom_bounds (dictionary, optional) – Optional lower and upper bounds for the equations of motion, default is
(0.0, 0.0)for each equation making them equality constraints. Dictionary is a mapping of equation of motion integer indices to a tuple of a lower and upper bounds given as floats. The index integer corresponds to the order ofequations_of_motion. Example:{3: (0.0, np.inf)}would make the 4th equation of motion an inequality constraint that cannot be below zero. Beware of transforming essential differential equations into inequality constraints, as that is likely not desired. These are typically used only for additional path constraints.
- add_option(keyword, val)¶
Add a keyword/value option pair to the problem.
See the Ipopt documentaion for details on available options.
- Parameters:
keyword (str) – Option name.
val (str, int or float) – Value of the option. The type of val should match the option definition as described in the Ipopt documentation.
- property bounds¶
Returns the bounds dictionary that maps tupples of floats to the unknown variables.
- check_bounds_conflict(free)[source]¶
Ascertains that the initial guesses for all variables are within the limits prescribed by their respective bounds. Raises a ValueError if for any variable the initial guess is outside its bounds, or if the lower bound is greater than the upper bound.
- Parameters:
free (array_like, shape(n*N + q*N + r + s, )) – Initial guess given to solve.
- Raises:
ValueError – If the lower bound for a variable or for an equation of motion is greater than its upper bound,
optymay not break, but the solution will likely not be correct. Hence a ValueError is raised in such as case. If the initial guess for any variable is outside its bounds, a ValueError is raised.
- close()¶
Deallocate memory resources used by the Ipopt package.
Called implicitly by the
Problemclass destructor.
- constraints(free)[source]¶
Returns the value of the constraint functions given a solution to the problem.
- Parameters:
free (ndarray, (n*N + q*N + r + s, )) – A solution to the optimization problem in the canonical form.
- Returns:
constraints_val – The value of the constraint function.
- Return type:
ndarray, shape(M*(N - 1) + o, )
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of unknown state trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals
o : number of instance constraints
- create_linear_initial_guess(end_time=1.0)[source]¶
Creates an initial guess that is the linear interpolation between exact instance constraints. Please see the notes for more information.
- Parameters:
end_time (float, optional (default=1.0)) – In case of a variable time interval, this is the assumed duration of the simulation.
- Returns:
initial_guess – The initial guess for the free variables in the optimization problem.
- Return type:
ndarray shape(n*N + q*N + r + s)
Notes
Instance constraints which contain instances of other state variables are ignored.
Between successsive instances of a state variable, the values are interpolated linearly.
If bounds exist for unknown input trajectories or unknown parameters, the values are set to the midpoint of the interval of the bounds.
If bounds exist for the variable time interval, the value is set to the midpoint of its bounds. This will override the value of
end_time.If one of the range limit of a bound is
-np.infornp.inf, the value is set to the other finite limit of bound.All else is set to zero.
- property eom_bounds¶
Returns the equation of motion bounds dictionary that maps tupples of floats to the equation of motion index.
- extract_values(free, *variables)[source]¶
Returns the numerical values of the free variables.
- Parameters:
free (ndarray, shape(n*N + q*N + r + s)) – The free optimization vector of the system, required if var is an unknown optimization variable.
variables (Symbol or Function()(time), len(d)) – One or more of the known or unknown variables in the problem.
- Returns:
values – The numerical values of the variables. The shape depends on how many variables and whether they are trajectories or parameters.
- Return type:
ndarray
- fill_free(free, values, *variables)[source]¶
Replaces the values in a vector shaped the same as the free optimization vector corresponding to the variable names.
- Parameters:
free (ndarray, shape(n*N + q*N + r + s, )) – Vector to replace values in.
values (ndarray, shape(N,) or float) – Numerical values to insert, arrays for each variable must be in order of monotonic time and then stacked in order variables. The shape depends on how many variables and whether they are trajectories or parameters.
varables (Symbol or Function()(time)) – One or more of the unknown optimization variables in the problem.
- get_current_iterate(scaled=False)¶
Return the current iterate vectors during an Ipopt solve
The iterate contains vectors for primal variables, bound multipliers, constraint function values, and constraint multipliers. Here, the constraints are treated as a single function rather than separating equality and inequality constraints. This method can only be called during an intermediate callback.
Only supports Ipopt >=3.14.0
- Parameters:
scaled (
bool) – Whether the scaled iterate vectors should be returned- Returns:
A dict containing the iterate vector with keys
"x","mult_x_L","mult_x_U","g", and"mult_g". If iterate vectors cannot be obtained,Noneis returned.- Return type:
dictor None
- get_current_violations(scaled=False)¶
Return the current violation vectors during an Ipopt solve
Violations returned are primal variable bound violations, bound complementarities, the gradient of the Lagrangian, constraint violation, and constraint complementarity. Here, the constraints are treated as a single function rather than separating equality and inequality constraints. This method can only be called during an intermediate callback.
Only supports Ipopt >=3.14.0
- Parameters:
scaled (
bool) – Whether to scale the returned violations- Returns:
A dict containing the violation vector with keys
"x_L_violation","x_U_violation","compl_x_L","compl_x_U","grad_lag_x","g_violation", and"compl_g". If violation vectors cannot be obtained,Noneis returned.- Return type:
dictor None
- gradient(free)[source]¶
Returns the value of the gradient of the objective function given a solution to the problem.
- Parameters:
free (ndarray, (n*N + q*N + r + s, )) – A solution to the optimization problem in the canonical form.
- Returns:
gradient_val – The value of the gradient of the objective function.
- Return type:
ndarray, shape(n*N + q*N + r + s, 1)
Notes
N : number of collocation nodes
n : number of unknown state trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals
- intermediate(*args)[source]¶
This method is called at every optimization iteration. Not for pubic use.
- jacobian(free)[source]¶
Returns the non-zero values of the Jacobian of the constraint function.
- Returns:
jac_vals – Non-zero Jacobian values in triplet format.
- Return type:
ndarray, shape((2*n + q + r + s)*(M*(N - 1)) + o, )
- jacobianstructure()[source]¶
Returns the sparsity structure of the Jacobian of the constraint function.
- Returns:
jac_row_idxs (ndarray, shape(2*n + q + r + s, )) – The row indices for the non-zero values in the Jacobian.
jac_col_idxs (ndarray, shape(M*(N - 1) + o, )) – The column indices for the non-zero values in the Jacobian.
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of unknown state trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals
o : number of instance constraints
- objective(free)[source]¶
Returns the value of the objective function given a solution to the problem.
- Parameters:
free (ndarray, shape(n*N + q*N + r + s, )) – A solution to the optimization problem in the canonical form.
- Returns:
obj_val – The value of the objective function.
- Return type:
float
Notes
N : number of collocation nodes
n : number of unknown state trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals
- parse_free(free)[source]¶
Parses the free parameters vector and returns it’s components.
- Parameters:
free (ndarray, shape(n*N + q*N + r + s)) – The free parameters of the system.
- Returns:
states (ndarray, shape(n, N)) – The array of n states through N time steps.
specified_values (ndarray, shape(q, N) or shape(N,), or None) – The array of q specified inputs through N time steps.
constant_values (ndarray, shape(r,)) – The array of r constants.
time_interval (float) – The time between collocation nodes. Only returned if
variable_durationisTrue.
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of unknown state trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals (s=1 if
variable durationisTrueelse s=0)
- plot_constraint_violations(
- vector,
- axes=None,
- subplots=False,
- show_bounds=False,
Returns an axis with the state constraint violations plotted versus node number and the instance constraints as a bar graph.
- Parameters:
vector (ndarray, (n*N + q*N + r + s, )) – The initial guess, solution, or any other vector that is in the canonical form.
axes (ndarray of AxesSubplot, optional.) – If given, it is the user’s responsibility to provide the correct number of axes.
subplots (boolean, optional.) – If True, the equations of motion will be plotted in a separate plot for each equation of motion. The default is False. If a user wants to provide the axes, it is recommended to run once without providing axes, to see how many are needed.
show_bounds (boolean, optional.) – If True and if
eom_boundsare given, and ifsubplotsis True the range of the bounded equations of motion will be shown. Otherwise the violations of the bounds will be shown. Default is False. If number of equations of motion is larger than one and subplots is False, only the violations are plotted, regardless of the value ofshow_bounds.
- Returns:
axes – A matplotlib axes with the constraint violations plotted. If the uses gives at least two axis, the method will tell the user how many are needed, unless the correct amount is given.
- Return type:
ndarray of AxesSubplot
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of unknown state trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals
If
eom_boundsare given as \(a \leq eom \leq b\) andsubplots = True, andshow_boundsis True the values of the respective eoms are plotted and their bounds are shown as dashed lines.if
eom_boundsare given andsubplots = False, the eom violations are plotted. The violations are calculated as follows:eom - a if eom < a
eom - b if eom > b
0 otherwise.
- plot_jacobian_sparsity(ax=None)[source]¶
Returns an axis with the sparsity pattern of the NLP Jacobian.
- plot_objective_value()[source]¶
Returns an axis with the objective value plotted versus the optimization iteration. solve() must be run first.
- plot_trajectories(
- vector,
- axes=None,
- show_bounds=False,
Returns the axes for two plots. The first plot displays the state trajectories versus time and the second plot displays the input trajectories versus time.
- Parameters:
vector (ndarray, (n*N + q*N + r + s, )) – The initial guess, solution, or any other vector that is in the canonical form.
axes (ndarray of AxesSubplot, shape(n + m, )) – An array of matplotlib axes to plot to.
show_bounds (bool, optional) – If True, the bounds will be plotted in the plot of the respective trajectory.
- Returns:
axes – A matplotlib axes with the state and input trajectories plotted.
- Return type:
ndarray of AxesSubplot
Notes
N : number of collocation nodes
M : number of equations of motion
n : number of unknown state trajectories
m : number of input trajectories
q : number of unknown input trajectories
r : number of unknown parameters
s : number of unknown time intervals
- set_problem_scaling(
- obj_scaling=1.0,
- x_scaling=None,
- g_scaling=None,
Optional function for setting scaling parameters for the problem.
To use the scaling parameters set the option
nlp_scaling_methodtouser-scaling.- Parameters:
obj_scaling (float) – Determines, how Ipopt should internally scale the objective function. For example, if this number is chosen to be 10, then Ipopt solves internally an optimization problem that has 10 times the value of the original objective. In particular, if this value is negative, then Ipopt will maximize the objective function instead of minimizing it.
x_scaling (array-like, shape(n, )) – The scaling factors for the variables. If
None, no scaling is done.g_scaling (array-like, shape(m, )) – The scaling factors for the constrains. If
None, no scaling is done.
- solve(
- free,
- lagrange=[],
- zl=[],
- zu=[],
- respect_bounds=False,
Returns the optimal solution and an info dictionary.
Solves the posed optimization problem starting at point x.
- Parameters:
x (array-like, shape(n*N + q*N + r + s, )) – Initial guess.
lagrange (array-like, shape(n*(N-1) + o, ), optional (default=[])) – Initial values for the constraint multipliers (only if warm start option is chosen).
zl (array-like, shape(n*N + q*N + r + s, ), optional (default=[])) – Initial values for the multipliers for lower variable bounds (only if warm start option is chosen).
zu (array-like, shape(n*N + q*N + r + s, ), optional (default=[])) – Initial values for the multipliers for upper variable bounds (only if warm start option is chosen).
respect_bounds (bool, optional (default=False)) – If True, the initial guess is checked to ensure that it is within the bounds, and a ValueError is raised if it is not. If False, the initial guess is not checked.
- Returns:
x (
numpy.ndarray, shape`(n*N + q*N + r + s, )`) – Optimal solution.info (
dictwith the following entries) –x:numpy.ndarray, shape`(n*N + q*N + r + s, )`optimal solution
g:numpy.ndarray, shape`(M*(N-1) + o, )`constraints at the optimal solution
obj_val:floatobjective value at optimal solution
mult_g:numpy.ndarray, shape`(M*(N-1) + o, )`final values of the constraint multipliers
mult_x_L:numpy.ndarray, shape`(M*N + q*N + r + s, )`bound multipliers at the solution
mult_x_U:numpy.ndarray, shape`(M*N + q*N + r + s, )`bound multipliers at the solution
status:intgives the status of the algorithm
status_msg:strgives the status of the algorithm as a message
- time_vector(solution=None, start_time=0.0)[source]¶
Returns the time array.
- Parameters:
solution (ndarray, shape(n*N + q*N + r + s,), optional) – Solution to to problem; required if the time interval is variable.
start_time (float, optional) – Initial time; default is
0.0.
- Returns:
time_vector – The array of time instances.
- Return type:
ndarray, shape(num_collocation_nodes,)
parameter_identification.py¶
- opty.parameter_identification.objective_function(
- free,
- num_dis_points,
- num_states,
- dis_period,
- time_measured,
- y_measured,
Returns the norm of the difference in the measured and simulated output.
- Parameters:
free (ndarray, shape(n*N + q*N + r,)) – The flattened state array with n states at N time points, q input trajectories and N time points, and the r free model constants.
num_dis_points (integer) – The number of model discretization points.
num_states (integer) – The number of system states.
dis_period (float) – The discretization time interval.
y_measured (ndarray, shape(M, o)) – The measured trajectories of the o output variables at each sampled time instance.
- Returns:
cost – The cost value.
- Return type:
float
Notes
This assumes that the states are ordered:
[coord1, …, coordn, speed1, …, speedn]
y_measured is interpolated at the discretization time points and compared to the model output at the discretization time points.
- opty.parameter_identification.objective_function_gradient(
- free,
- num_dis_points,
- num_states,
- dis_period,
- time_measured,
- y_measured,
Returns the gradient of the objective function with respect to the free parameters.
- Parameters:
free (ndarray, shape(n*N + q*N + r,)) – The flattened state array with n states at N time points, q input trajectories and N time points, and the r free model constants.
num_dis_points (integer) – The number of model discretization points.
num_states (integer) – The number of system states.
dis_period (float) – The discretization time interval.
y_measured (ndarray, shape(M, o)) – The measured trajectories of the o output variables at each sampled time instance.
- Returns:
gradient – The gradient of the cost function with respect to the free parameters.
- Return type:
ndarray, shape(n*N + q*N + r,)
Warning
This is currently only valid if the model outputs (and measurements) are simply the states. The chain rule will be needed if the function output_equations() is more than a simple selection.
- opty.parameter_identification.output_equations(x)[source]¶
Returns the outputs of the system. For now just the an array of the generalized coordinates.
- Parameters:
x (ndarray, shape(N, n)) – The trajectories of the system states.
- Returns:
y – The trajectories of the generalized coordinates.
- Return type:
ndarray, shape(N, o)
Notes
The order of the states is assumed to be:
[coord_1, …, coord_{n/2}, speed_1, …, speed_{n/2}]
[q_1, …, q_{n/2}, u_1, …., u_{n/2}]
As this is what generate_ode_function creates.
utils.py¶
- opty.utils.create_objective_function(
- objective,
- state_symbols,
- unknown_input_trajectories,
- unknown_parameters,
- num_collocation_nodes,
- node_time_interval,
- integration_method='backward euler',
- time_symbol=t,
Creates function to evaluate the objective and objective gradient.
- Parameters:
objective (Expr) – Symbolic objective function to be minimized. It should solely depend on the states, unknown inputs, and unknown parameters. Any known inputs or parameters should be substituted beforehand. Additionally, the objective function can contain non-nested indefinite integrals of time, e.g.
Integral(f(t)**2, t).state_symbols (iterable of Function()(t)) – An iterable containing all
nof the SymPy functions of time which represent the states in the equations of motion.unknown_input_trajectories (iterable of Function()(t)) – An iterable containing all
qof the SymPy functions of time which represent the unknown input trajectories in the equations of motion.unknown_parameters (iterable of Symbol) – An iterable containing all
rof the SymPy symbols which represent the unknown parameters in the equations of motion.num_collocation_nodes (int) – Number of collocation nodes, i.e. the number of time steps.
node_time_interval (float) – The value of the time interval. The default is 1.0, as this term only appears in the objective function as a scaling factor.
integration_method (str, optional) – The method used to integrate the system. The default is
"backward euler".time_symbol (Symbol, optional) – If not supplied,
sympy.physics.mechanics.dynamicsymbols._tis used.
- opty.utils.parse_free(free, n, q, N, variable_duration=False)[source]¶
Parses the free parameters vector and returns it’s components.
- Parameters:
free (ndarray, shape(n*N + q*N + r + s)) – The free parameters of the system.
n (integer) – The number of states.
q (integer) – The number of free specified inputs.
N (integer) – The number of time steps.
variable_duration (boolean, optional) – If True, the last value in
freeis the node time interval and it will be returned.
- Returns:
states (ndarray, shape(n, N)) – The array of n states through N time steps.
specified_values (ndarray, shape(q, N) or shape(N,), or None) – The array of q specified inputs through N time steps.
constant_values (ndarray, shape(r,)) – The array of r constants.
time_interval (float) – The time between collocation nodes. Only returned if
variable_durationisTrue.