csnlp.multistart.ParallelMultistartNlp#

class csnlp.multistart.ParallelMultistartNlp(*args, starts, parallel_kwargs=None, **kwargs)[source]#

Bases: MultistartNlp[SymType], Generic[SymType]

A class that solves an NLP problem multiple times, with different initial starting conditions, via parallelization of the computations via joblib.

Parameters:
args, kwargs

See inherited csnlp.Nlp.__init__.

startsint

A positive integer for the number of multiple starting guesses to optimize.

parallel_kwargs: dict, optional

A dictionary with keyword arguments to be used to instantiate the parallel joblib.Parallel backend. By default, None, in which case the parallel backend is instantiated with default arguments.

Raises:
ValueError

Raises if the scenario number is invalid.

Methods

constraint(name, lhs, op, rhs[, soft, simplify])

Adds a constraint to the NLP problem, e.g., \(lhs \le rhs\).

init_solver([opts, solver, type])

Initializes the solver for this NLP with the given options.

initialize_parallel()

Initializes the parallel backend.

is_wrapped(*_, **__)

Gets whether the NLP instance is wrapped or not by the given wrapper type.

minimize(objective)

Sets the objective function to be minimized.

parameter(name[, shape])

Adds a parameter to the NLP scheme.

refresh_solver()

Refresh and resets the internal solver function (with the same options, if previously set).

remove_constraints(name[, idx])

Removes one or more (equality or inequality) constraints from the problem.

remove_variable_bounds(name, direction[, idx])

Removes one or more lower and/or upper bounds from the given variable

solve([pars, vals0])

Solves the NLP optimization problem.

solve_multi([pars, vals0, return_all_sols])

Solves the NLP with multiple initial conditions.

terminate_parallel()

Terminates the parallel backend.

to_function(name, ins, outs[, name_in, ...])

Converts the optimization problem to an SX or MX symbolic casadi.Function.

variable(name[, shape, discrete, lb, ub])

Adds a variable to the NLP problem.

Attributes

constraints

Gets the constraints of the NLP scheme.

debug

Gets debug information on the NLP scheme.

discrete

Gets the boolean array indicating which variables are discrete.

dual_variables

Gets the dual variables of the NLP scheme.

f

Gets the objective of the NLP scheme, which is None if not set previously set via the minimize method.

g

Gets the equality constraint expressions of the NLP scheme in vector form.

h

Gets the inequality constraint expressions of the NLP scheme in vector form.

h_lbx

Gets the inequalities cor to lbx, i.e., \(lbx - x\).

h_ubx

Gets the inequalities due to ubx, i.e., \(x - ubx\).

is_multi

Flag to indicate that this is a multistart NLP.

lam

Gets the dual variables of the NLP scheme in vector form.

lam_g

Gets the dual variables of the equality constraints of the NLP scheme in vector form.

lam_h

Gets the dual variables of the inequality constraints of the NLP scheme in vector form.

lam_lbx

Gets the dual variables of the primary variables lower bound constraints of the NLP scheme in vector form.

lam_ubx

Gets the dual variables of the primary variables upper bound constraints of the NLP scheme in vector form.

lbx

Gets the lower bound constraints of primary variables of the NLP scheme in masked vector form.

ng

Number of equality constraints in the NLP scheme.

nh

Number of inequality constraints in the NLP scheme.

nonmasked_lbx_idx

Gets the indices of non-masked entries in lbx (or the full slice).

nonmasked_ubx_idx

Gets the indices of non-masked entries in ubx (or the full slice).

np

Number of parameters in the NLP scheme.

nx

Number of variables in the NLP scheme.

p

Gets the parameters of the NLP scheme.

parameters

Gets the parameters of the NLP scheme.

primal_dual

Gets the collection of primal-dual variables (usually, denoted as y)

solver

Gets the NLP optimization solver.

solver_opts

Gets the NLP optimization solver options.

starts

Gets the number of starts.

sym_type

Gets the CasADi symbolic type used in this NLP scheme.

ubx

Gets the upper bound constraints of primary variables of the NLP scheme in masked vector form.

unwrapped

Returns the original NLP of the wrapper.

variables

Gets the primal variables of the NLP scheme.

x

Gets the primary variables of the NLP scheme in vector form.

constraint(name, lhs, op, rhs, soft=False, simplify=True)#

Adds a constraint to the NLP problem, e.g., \(lhs \le rhs\).

Parameters:
namestr

Name of the new constraint. Must not be already in use.

lhscasadi.SX, MX, DM or numerical

Symbolic expression of the left-hand term of the constraint.

op: {“==”, “>=”, “<=”}

Operator relating the two terms.

rhscasadi.SX, MX, DM or numerical

Symbolic expression of the right-hand term of the constraint.

softbool, optional

If True, then a slack variable with appropriate size is added to the NLP to make the inequality constraint soft, and returned. This slack is automatically lower-bounded by 0, but remember to manually penalize its magnitude in the objective. Slacks are not supported for equality constraints. Defaults to False.

simplifybool, optional

Optionally simplies the constraint expression, but can be disabled.

Returns:
exprcasadi.SX or MX

The constraint expression in canonical form, i.e., \(g(x,p) = 0\) or \(h(x,p) \le 0\).

lamcasadi.SX or MX

The symbol corresponding to the constraint’s multipliers.

slackcasadi.SX or MX, optional

The slack variable in case of soft=True; otherwise, only a 2-tuple is returned.

Raises:
ValueError

Raises if there is already another constraint with the same name; or if the operator is not recognized.

NotImplementedError

Raises if a soft equality constraint is requested.

TypeError

Raises if the constraint is not symbolic.

Return type:

tuple[TypeVar(SymType, SX, MX), ...]

property constraints: dict[str, SymType]#

Gets the constraints of the NLP scheme.

property debug: NlpDebug | None#

Gets debug information on the NLP scheme.

property discrete: ndarray[tuple[Any, ...], dtype[bool]]#

Gets the boolean array indicating which variables are discrete.

property dual_variables: dict[str, SymType]#

Gets the dual variables of the NLP scheme.

property f: SymType | None#

Gets the objective of the NLP scheme, which is None if not set previously set via the minimize method.

property g: SymType#

Gets the equality constraint expressions of the NLP scheme in vector form.

property h: SymType#

Gets the inequality constraint expressions of the NLP scheme in vector form.

property h_lbx: SymType#

Gets the inequalities cor to lbx, i.e., \(lbx - x\).

property h_ubx: SymType#

Gets the inequalities due to ubx, i.e., \(x - ubx\).

init_solver(opts=None, solver='ipopt', type=None)#

Initializes the solver for this NLP with the given options.

Parameters:
optsdict[str, Any], optional

Options to be passed to the CasADi interface to the solver. Must not contain the "discrete" key, which is automatically set based on the variables’ domains. By default, None.

solverstr, optional

Type of solver to instantiate. For example, "ipopt" and "sqpmethod" trigger the instantiation of an NLP problem, while, e.g., "qrqp", "osqp", and "qpoases" of a conic one. However, the solver type can be overruled with the type argument. By default, "ipopt" is selected.

type“nlp”, “conic”, optional

Type of problem to instantiate. If "nlp", then the problem is forced to be instantiated with casadi.nlpsol. If "conic", then casadi.qpsol is forced instead. If None, then the problem type is selected automatically.

Raises:
ValueError

Raises if the given problem type is not recognized, or if the opts dict contains the

RuntimeError

Raises if the type of the problem cannot be inferred automatically (when the solver supports both conic and NLPs), if the specified solver plugin cannot be found, and if the objective has not yet been specified with minimize.

Return type:

None

initialize_parallel()[source]#

Initializes the parallel backend.

Return type:

None

is_multi: ClassVar[bool] = True#

Flag to indicate that this is a multistart NLP.

is_wrapped(*_, **__)#

Gets whether the NLP instance is wrapped or not by the given wrapper type.

Return type:

bool

property lam: SymType#

Gets the dual variables of the NLP scheme in vector form.

Notes

The dual variables are vertically concatenated in the following order: lam_g, lam_h, lam_lbx, lam_ubx.

property lam_g: SymType#

Gets the dual variables of the equality constraints of the NLP scheme in vector form.

property lam_h: SymType#

Gets the dual variables of the inequality constraints of the NLP scheme in vector form.

property lam_lbx: SymType#

Gets the dual variables of the primary variables lower bound constraints of the NLP scheme in vector form.

property lam_ubx: SymType#

Gets the dual variables of the primary variables upper bound constraints of the NLP scheme in vector form.

property lbx: MaskedArray#

Gets the lower bound constraints of primary variables of the NLP scheme in masked vector form.

minimize(objective)#

Sets the objective function to be minimized.

Parameters:
objectivecasadi SX or MX

A Symbolic variable dependent only on the NLP variables and parameters that needs to be minimized.

Raises:
ValueError

Raises if the objective is not scalar.

Return type:

None

property ng: int#

Number of equality constraints in the NLP scheme.

property nh: int#

Number of inequality constraints in the NLP scheme.

property nonmasked_lbx_idx: slice | ndarray[tuple[Any, ...], dtype[int64]]#

Gets the indices of non-masked entries in lbx (or the full slice).

property nonmasked_ubx_idx: slice | ndarray[tuple[Any, ...], dtype[int64]]#

Gets the indices of non-masked entries in ubx (or the full slice).

property np: int#

Number of parameters in the NLP scheme.

property nx: int#

Number of variables in the NLP scheme.

property p: SymType#

Gets the parameters of the NLP scheme.

parameter(name, shape=(1, 1))#

Adds a parameter to the NLP scheme.

Parameters:
namestr

Name of the new parameter. Must not be already in use.

shapetuple of 2 ints, optional

Shape of the new parameter. By default a scalar, i.e., (1, 1).

Returns:
casadi.SX or MX

The symbol for the new parameter.

Raises:
ValueError

Raises if there is already another parameter with the same name name.

Return type:

TypeVar(SymType, SX, MX)

property parameters: dict[str, SymType]#

Gets the parameters of the NLP scheme.

property primal_dual: SymType#

Gets the collection of primal-dual variables (usually, denoted as y)

\[\begin{split}y = \begin{bmatrix} x \\ \lambda \end{bmatrix},\end{split}\]

where \(x\) are the primal variables, and \(\lambda\) the dual variables (see x and lam, respectively).

refresh_solver()#

Refresh and resets the internal solver function (with the same options, if previously set).

Return type:

None

remove_constraints(name, idx=None)#

Removes one or more (equality or inequality) constraints from the problem.

Parameters:
namestr

Name of the constraint to be removed. The name will be used to identify if the constraint is an inequality or an equality constraint.

idxtuple of 2 ints or a list of, optional

A 2D index, or a list of 2D indices, of the constraint entries that must be removed. If not provided, then the constraint is removed entirely.

Return type:

None

Notes

This is a somewhat costly operation, so it is preferable to avoid creating in the first place constraints that will need to be eliminated. Moreover, this operation may compromise the results already obtained in, e.g., sensitivity analysis, because it changes the underlying NLP problem and there is no way to invalidate any user-arbitrary result obtained previously.

remove_variable_bounds(name, direction, idx=None)#

Removes one or more lower and/or upper bounds from the given variable

Parameters:
namestr

Name of the variable whose bounds must be modified

direction{“lb”, “ub”, “both”}

Which bound to modify.

idxtuple[int, int] or a list of, optional

A 2D index, or a list of 2D indices, of the variable entries whose corresponding lower/upper bounds must be removed, i.e., set to -/+ inf. If not provided, then all the bounds for that variable are removed.

Return type:

None

Notes

This is a somewhat costly operation, so it is preferable to avoid creating in the first place constraints that will need to be eliminated. Moreover, this operation may compromise the results already obtained in, e.g., sensitivity analysis, because it changes the underlying NLP problem and there is no way to invalidate any user-arbitrary result obtained previously.

solve(pars=None, vals0=None)#

Solves the NLP optimization problem.

Parameters:
parsdict[str, array_like], optional

Dictionary or structure containing, for each parameter in the NLP scheme, the corresponding numerical value. Can be None if no parameters are present.

vals0dict[str, array_like], optional

Dictionary or structure containing, for each variable in the NLP scheme, the corresponding initial guess. By default, initial guesses are not passed to the solver.

Returns:
solSolution

A solution object containing all the information.

Raises:
RuntimeError

Raises if the solver is un-initialized (see init_solver); or if not all the parameters are not provided with a numerical value.

Return type:

Solution[TypeVar(SymType, SX, MX)]

solve_multi(pars=None, vals0=None, return_all_sols=False, **_)[source]#

Solves the NLP with multiple initial conditions.

Parameters:
parsdict of (str, array_like) or iterable of, optional

An iterable that, for each multistart, contains a dictionary with, for each parameter in the NLP scheme, the corresponding numerical value. In case a single dict is passed, the same is used across all scenarions. Can be None if no parameters are present.

vals0dict of (str, array_like) or iterable of, optional

An iterable that, for each multistart, contains a dictionary with, for each variable in the NLP scheme, the corresponding initial guess. In case a single dict is passed, the same is used across all scenarions. By default None, in which case initial guesses are not passed to the solver.

return_all_solsbool, optional

If True, returns the solution of each multistart of the NLP; otherwise, only the best solution is returned. By default, False.

Returns:
Solution or list of Solutions

Depending on the flags return_all_sols, returns

  • the best solution out of all multiple starts

  • all the solutions (one per start).

Return type:

Union[Solution[TypeVar(SymType, SX, MX)], list[Solution[TypeVar(SymType, SX, MX)]]]

property solver: Function | None#

Gets the NLP optimization solver. Can be None, if the solver is not set with method init_solver.

property solver_opts: dict[str, Any]#

Gets the NLP optimization solver options. The dict is empty, if the solver options are not set with method init_solver.

property starts: int#

Gets the number of starts.

property sym_type: type[SymType]#

Gets the CasADi symbolic type used in this NLP scheme.

terminate_parallel()[source]#

Terminates the parallel backend.

Return type:

None

to_function(name, ins, outs, name_in=None, name_out=None, opts=None, mx_prewrap=False)#

Converts the optimization problem to an SX or MX symbolic casadi.Function. If the NLP is modelled in SX, the function can be pre-wrapped in MX.

Parameters:
namestr

Name of the function.

inssequence of casadi.SX or MX

Input variables of the function. These must be expressions providing the parameters of the NLP and the initial conditions of the primal variables x.

outssequence of casadi.SX or MX

Output variables of the function. These must be expressions depending on the primal variable x, parameters p, and dual variables lam_g, lam_h, lam_lbx, lam_ubx of the NLP.

name_insequence of str, optional

Name of the inputs, by default None.

name_outsequence of str, optional

Name of the outpus, by default None.

optsdict[Any, Any], optional

Options to be passed to casadi.Function, by default None.

mx_prewrapbool, optional

If True, wraps the CasADi interface in an MX wrapper prior to turning it into the function. This is useful when the NLP is defined in SX but the interface is only supported in MX. By default, False.

Returns:
casadi.Function

The NLP solver as an instance of casadi.Function.

Raises:
RuntimeError

Raises if the solver is uninitialized, or if the input or output expressions have free variables that are not provided or cannot be computed by the solver.

Return type:

Function

property ubx: MaskedArray#

Gets the upper bound constraints of primary variables of the NLP scheme in masked vector form.

property unwrapped: Nlp[SymType]#

Returns the original NLP of the wrapper.

variable(name, shape=(1, 1), discrete=False, lb=-inf, ub=inf)#

Adds a variable to the NLP problem.

Parameters:
namestr

Name of the new variable. Must not be already in use.

shapetuple of 2 ints, optional

Shape of the new variable. By default, a scalar.

discretebool, optional

Flag indicating if the variable is discrete. Defaults to False.

lb, ub: array_like, optional

Lower and upper bounds of the new variable. By default, unbounded. If provided, their dimension must be broadcastable.

Returns:
varcasadi.SX or MX

The symbol of the new variable.

lam_lbcasadi.SX or MX

The symbol corresponding to the new variable lower bound constraint’s multipliers. The shape of the multiplier is equal to the number of relevant lower bounds (i.e., \(\neq \pm \infty\)), so it may differ from the shape of the variable itself. This behaviour can be disabled by setting remove_redundant_x_bounds=False.

lam_ubcasadi.SX or MX

Same as above, for upper bound.

Raises:
ValueError

Raises if there is already another variable with the same name; or if any element of the lower bound is larger than the corresponding lower bound element.

Return type:

tuple[TypeVar(SymType, SX, MX), TypeVar(SymType, SX, MX), TypeVar(SymType, SX, MX)]

property variables: dict[str, SymType]#

Gets the primal variables of the NLP scheme.

property x: SymType#

Gets the primary variables of the NLP scheme in vector form.

Examples using csnlp.multistart.ParallelMultistartNlp#

A simple problem with multiple minima

A simple problem with multiple minima