mp.opt_model
- class mp.opt_model
Bases:
handlemp.opt_model- Mathematical programming and optimization model class.mm = mp.opt_model mm = mp.opt_model(s) mm = mp.opt_model(mm0) mm = mp.opt_model(om)
This class implements the model object used to encapsulate a given mathematical programming or optimization problem formulation. It allows for access to variables, constraints and costs in named blocks, keeping track of the ordering and indexing of the blocks as variables, constraints and costs are added to the model.
- mp.opt_model Properties:
var- MP Set Manager for variableslin- MP Set Manager for linear constraintsqcn- MP Set Manager for quadratic constraintsnle- MP Set Manager for nonlinear equality constraintsnli- MP Set Manager for nonlinear inequality constraintsqdc- MP Set Manager for quadratic costsnlc- MP Set Manager for general nonlinear costsprob_type- problem type, cached result ofproblem_type()userdata- arbitrary user data
- mp.opt_model Methods:
opt_model()- constructor, optionally copying from struct or existing objectget_set_types()- list of names of properties of set types managed by this classcopy()- make a duplicate of the objectto_struct()- convert object data to a structfrom_struct()- copy object data from a structget_idx()- returnidxstruct for vars, constraints, costsget_user_data()- used to retrieve values of user dataproblem_type()- return string identifying type of mathematical programis_mixed_integer()- return true if model is mixed integer, false otherwiseis_solved()- return true if model has been solvedsolve()- solve the modelhas_parsed_soln()- return true if model has a parsed solutionparse_soln()- parse solution vector and shadow prices by all named setsdisplay()- display the objectdisplay_header()- display header, before each set typedisplay_footer()- display footer, after each set typedisplay_soln()- display solution values
Example:
mm = mp.opt_model; mm.var.add('y', 2, y0, ymin); mm.var.add('z', 2, z0, [], zmax); mm.lin.add(mm.var, 'lincon1', A1, b1, b1); mm.lin.add(mm.var, 'lincon2', A2, [], u2, {'y'}); mm.qdc.add(mm.var, 'cost', H, []); prob_type = mm.problem_type(); if ~mm.is_solved() [x, f, exitflag, output, lambda] = mm.solve(); end mm.display_soln();
Replaces the now deprecated legacy
opt_modelclass and its base class,mp_idx_manager.See also
mp.set_manager.- Constructor Summary
- opt_model(varargin)
Constructor.
mm = mp.opt_model() mm = mp.opt_model(a_struct) mm = mp.opt_model(an_mm) mm = mp.opt_model(an_om)
Optionally copies data from (duplicates) a struct or existing mathematical model object.
- Input:
a_struct (struct) – a struct with the stucture obtained by converting an
mp.opt_modelobject and its sub-objects to a structan_mm (
mp.opt_model) – existing mathematical model (mp.opt_model) objectan_om (
opt_model) – existing legacy mathematical model (opt_model) object
- Property Summary
- var
(
mp.sm_variable) MP Set Manager for variables
- lin
(
mp.sm_lin_constraint) MP Set Manager for linear constraints
- qcn
(
mp.sm_quad_constraint) MP Set Manager for quadratic constraints
- nle
(
mp.sm_nln_constraint) MP Set Manager for nonlinear equality constraints
- nli
(
mp.sm_nln_constraint) MP Set Manager for nonlinear inequality constraints
- qdc
(
mp.sm_quad_cost) MP Set Manager for quadratic costs
- nlc
(
mp.sm_nln_cost) MP Set Manager for general nonlinear costs
- prob_type = ''
(char array) problem type, cached result of
problem_type()
- soln = struct('eflag',[], ... 'lambda',[])
(struct) results of
solve(), with fields:'eflag'- exit flag'output'- algorithm code ('alg') & solver-specific fields'x'- solution vector'f'- final (objective) function value'jac'- Jacobian (if available) for LEQ/NLEQ'lambda'- struct of constraint shadow prices
- userdata = struct()
(struct) arbitrary user data
- Method Summary
- get_set_types(mm)
List of names of properties of set types managed by this class.
st = mm.get_set_types();
- Output:
st (cell array) – list of set types, namely:
{'var', 'lin', 'qcn', 'nle', 'nli', 'qdc', 'nlc'}
- copy(mm)
Duplicate the object.
new_mm = mm.copy()
- Output:
new_mm (
mp.opt_model) – duplicate of original object
Make a duplicate of the object, including duplicates of all contained objects.
- to_struct(mm)
Convert object data to a struct.
s = mm.to_struct()
Converts the object data to a struct that can later be converted back to an identical object using
mp.struct2object(). Useful for saving the object data to a MAT-file in Octave.
- from_struct(mm, s)
Copy object data from a struct.
mm.from_struct(s)
Called by function
mp.struct2object(), after creating the object to copy the object data from a struct. Useful for recreating the object after loading struct data from a MAT-file in Octave.
- get_idx(mm, varargin)
Return
idxstruct for vars, constraints, costs.vv = mm.get_idx() [vv, ll] = mm.get_idx() [vv, ll, nne] = mm.get_idx() [vv, ll, nne, nni] = mm.get_idx() [vv, ll, nne, nni, qq] = mm.get_idx() [vv, ll, nne, nni, qq, nnc] = mm.get_idx() [vv, ll, nne, nni, qq, nnc, qqcn] = mm.get_idx()
Returns the
idxproperty of each of the set manager objects, with the beginning and ending index value and the number of elements for each named block. Thei1field is a struct with all of the starting indices,iNcontains all the ending indices, andNcontains all the sizes. Each is a struct whose fields are the named blocks.Alternatively, you can specify the property name of the set type directly as inputs.
[idx1, idx2, ...] = mm.get_idx(set_type1, set_type2, ...)
- Inputs:
set_type<n> (char array) – name of set type, valid options are:
'var'- variables'lin'- linear constraints'qcn'- quadratic constraints'nle'- nonlinear equality constraints'nli'- nonlinear inequality constraints'qdc'- quadratic costs'nlc'- general nonlinear costs
- Outputs:
vv (struct) –
mm.var.idxll (struct) –
mm.lin.idxnne (struct) –
mm.nle.idxnni (struct) –
mm.nli.idxqq (struct) –
mm.qdc.idxnnc (struct) –
mm.nlc.idxqqcn (struct) –
mm.qcn.idxidx<n> (struct) –
idxproperty of property indicated by respective input
Examples:
[vv, ll, nne] = mm.get_idx(); [vv, ll, qq] = mm.get_idx('var', 'lin', 'qdc'); [ll, nne, nni] = mm.get_idx('lin', 'nle', 'nli');
For a variable block named
zwe have …vv.i1.z- starting index forzin vectorxvv.iN.z- ending index forzin vectorxvv.N.z- number of elements inz
To extract a
zvariable fromx:z = x(vv.i1.z:vv.iN.z);
To extract the multipliers on a linear constraint set named
foo, wheremu_landmu_uare the full set of linear constraint multipliers:mu_l_foo = mu_l(ll.i1.foo:ll.iN.foo); mu_u_foo = mu_u(ll.i1.foo:ll.iN.foo);
The number of nonlinear equality constraints in a set named
bar:nbar = nne.N.bar;
Note: The following is preferable if you haven’t already called
get_idx()to getnne.nbar = mm.nle.get_N('bar');
If
z,foo, andbarare indexed sets, then you can replace them with something likez(i,j),foo(i,j,k)orbar(i)in the examples above.
- get_userdata(mm, name)
Used to retrieve values of user data.
val = mm.get_userdata(name)
Returns the value specified by the given name or an empty matrix if userdata with
namedoes not exist.- Inputs:
name (char array) – name of user data to return
- Outputs:
val (arbitrary) – the arbitrary user data stored under the specified name
This function allows the user to retrieve any arbitrary data that was saved in the object for later use. Data for a given
nameis saved by assigning it tomm.userdata.(name).This can be useful, for example, when using a user function to add variables or constraints, etc. Suppose some special indexing is constructed when adding some variables or constraints. This indexing data can be stored and used later to “unpack” the results of the solved case.
- problem_type(mm, recheck)
Return string identifying type of mathematical program.
prob_type = mm.problem_type() prob_type = mm.problem_type(recheck)
Returns a string identifying the type of mathematical program represented by the current model, based on the variables, costs, and constraints that have been added to the model. Used to automatically select an appropriate solver.
Linear and nonlinear equations are models with no costs, no inequality constraints, and an equal number of continuous variables and equality constraints. If the number of variables in a nonlinear equation model is one more than the number of constraints, it is a parameterized nonlinear equation.
The output value is cached for future calls, but calling with a true value for the optional
recheckargument will force it to recheck in case the problem type has changed due to modifying the variables, constraints or costs in the model.- Input:
recheck (logical) – true to force a reevaluation instead of possibly returning a cached value
- Output:
prob_type (char array) – problem type, one of the following strings:
'LEQ'- linear equations'NLEQ'- nonlinear equations'PNE'- parameterized nonlinear equations'LP'- linear program'QP'- quadratic program'NLP'- nonlinear program'MILP'- mixed-integer linear program'MIQP'- mixed-integer quadratic program'MINLP'- mixed-integer nonlinear program
- is_mixed_integer(mm)
Return true if model is mixed integer, false otherwise.
TorF = mm.is_mixed_integer()
- Outputs:
TorF (logical) – true or false, indicating whether any of the variables are binary or integer
- is_solved(mm)
Return true if model has been solved.
TorF = mm.is_solved()
- Outputs:
TorF (logical) – true or false, indicating whether the model solution is available
- solve(mm, opt)
Solve the model.
x = mm.solve() [x, f] = mm.solve() [x, f, exitflag] = mm.solve() [x, f, exitflag, output] = mm.solve() [x, f, exitflag, output, jac] = mm.solve() (LEQ/NLEQ problems) [x, f, exitflag, output, lambda] = mm.solve() (other problem types) [x ...] = mm.solve(opt)
Solves the model using one of the following, depending on the problem type: mp_linsolve,
nleqs_master(),pnes_master(),qps_master(),qcqps_master(),miqps_master(),nlps_master().- Inputs:
opt (struct) – optional options struct with the following fields, all of which are also optional (default values shown in parentheses)
alg('DEFAULT') - determines which solver to use, list of relevant problem types are listed in parens next to each'DEFAULT'- automatic, depending on problem type, uses the the first available of:Type
Solver Precedence
LP
Gurobi, CPLEX, MOSEK, linprog (if MATLAB), HIGHS, GLPK, BPMPD, MIPS
QP
Gurobi, CPLEX, MOSEK, quadprog (if MATLAB), HIGHS, BPMPD, MIPS
QCQP
IPOPT, Artelys Knitro, FMINCON, MIPS
MILP
Gurobi, CPLEX, MOSEK, Opt Tbx (intlingprog), HIGHS, GLPK
MIQP
Gurobi, CPLEX, MOSEK
NLP
MIPS
MINLP
Artelys Knitro (not yet implemented)
LEQ
built-in backslash operator
NLEQ
Newton’s method
PNE
predictor/corrector method
'BPMPD'- (LP, QP) BPMPD_MEX'CLP'- (LP, QP) CLP'CPLEX'- (LP, QP, MILP, MIQP) CPLEX'FD'- (NLEQ) fast-decoupled Newon’s method'FMINCON'- (QCQP, NLP) FMINCON, MATLAB Optimization Toolbox'FSOLVE'- (NLEQ) FSOLVE, MATLAB Optimization Toolbox'GLPK'- (LP, MILP) GLPK'GS'- (NLEQ) Gauss-Seidel'GUROBI'- (LP, QP, QCQP, MILP, MIQP) Gurobi'HIGHS'- (LP, QP, MILP) HiGHS, https://highs.dev'IPOPT'- (LP, QP, QCQP, NLP) IPOPT, requires MEX interface to IPOPT solver https://github.com/coin-or/Ipopt'KNITRO'- (QCQP, NLP, MINLP) Artelys Knitro, requires Artelys Knitro solver https://www.artelys.com/solvers/knitro/'MIPS'- (LP, QP, QCQP, NLP) MIPS, MATPOWER Interior Point Solver, pure MATLAB implementation of a primal-dual interior point method, ifmips_opt.step_control = 1it uses MIPS-sc, a step controlled variant of MIPS'MOSEK'- (LP, QP, MILP, MIQP) MOSEK'NEWTON'- (NLEQ) Newton’s method'OSQP'- (LP, QP) OSQP, https://osqp.org'OT'- (LP, QP, MILP) MATLAB Optimization Toolbox, linprog, quadprog or intlinprog
verbose(0) - controls level of progress output displayed:0 = no progress output
1 = some progress output
2 = verbose progress output
bp_opt- options vector forbp()(BPMPD)clp_opt- options vector for CLPcplex_opt- options struct for CPLEXfd_opt- options struct for fast-decoupled Newton’s method,nleqs_fd_newton()fmincon_opt- options struct forfmincon()fsolve_opt- options struct forfsolve()glpk_opt- options struct for GLPKgrb_opt- options struct for Gurobigs_opt- options struct for Gauss-Seidel method,nleqs_gauss_seidel()highs_opt- options struct for HiGHSintlinprog_opt- options struct forintlinprog()ipopt_opt- options struct for IPOPTknitro_opt- options struct for Artelys Knitroleq_opt- options struct formplinsolve(), with optional fieldssolverandoptcorresponding to respectivemplinsolve()args, andthreshspecifying a threshold on the absolute value of any elementx, above whichexitflagwill be set to 0linprog_opt- options struct forlinprog()mips_opt- options struct formips()mosek_opt- options struct for MOSEKnewton_opt- options struct for Newton method,nleqs_newton()osqp_opt- options struct for OSQPquadprog_opt- options struct forquadprog()parse_soln(0) - flag that specifies whether or not to call theparse_soln()method and place the return values inmm.soln.price_stage_warn_tol(1e-7) - tolerance on objective fcn value and primal variable relative match required to avoid mismatch warning message if mixed integer price computation stage is not skippedrelax_integer(0) - relax integer constraints, if trueskip_prices(0) - flag that specifies whether or not to skip the price computation stage for mixed integer problems, in which the problem is re-solved for only the continuous variables, with all others being constrained to their solved valuesx0(empty) - optional initial value ofx, overrides value stored in model (ignored by some solvers)
- Outputs:
x (double) – solution vector
f (double) – final (objective) function value
exitflag (integer) – exit flag
1 = converged
0 or negative values = solver specific failure codes
output (struct) – output struct with the following fields:
alg- algorithm code of solver usedet- elapsed time (sec)(others) - solver specific fields
jac (double) – final Jacobian matrix (if available, for LEQ/NLEQ problems)
lambda (struct) – (for all problem types except LEQ, NLEQ, and PNE) Langrange and Kuhn-Tucker multipliers on the constraints, struct with fields:
eqnonlin- nonlinear equality constraintsineqnonlin- nonlinear inequality constraintsmu_l- lower (left-hand) limit on linear constraintsmu_u- upper (right-hand) limit on linear constraintslower- lower bound on optimization variablesupper- upper bound on optimization variables
See also
mp_linsolve,nleqs_master(),pnes_master(),qps_master(),qcqps_master(),miqps_master(),nlps_master().
- has_parsed_soln(mm)
Return true if model has a parsed solution.
TorF = mm.has_parsed_soln()
- parse_soln(mm, stash)
Parse solution vector and shadow prices by all named sets.
ps = mm.parse_soln() mm.parse_soln(stash)
For a solved model,
parse_soln()returns a struct of parsed solution vector and shadow price values for each named set of variables and constraints.- Input:
stash (logical) – if true, individual parsed solutions are stored in the
solnproperty of the respective set type object.- Output:
ps (struct) – struct of parsed solution values with the following fields, where each of the terminal elements is a struct with fields corresponding to the respective named sets.
var- variable solution struct with fields:val- values of variablesmu_l- shadow prices on variable lower boundsmu_u- shadow prices on variable upper bounds
lin- linear constraint solution struct with fields:mu_l- shadow prices on constraint lower boundsmu_u- shadow prices on constraint upper bounds
qcn- quadratic constraint solution struct with fields:mu_l- shadow prices on constraint lower boundsmu_u- shadow prices on constraint upper bounds
nle- nonlinear equality constraint solution struct with fields:lam- shadow prices on constraints
nli- nonlinear inequality constraint solution struct with fields:mu- shadow prices on constraints
The value of each element in the returned struct can be obtained via the
get_soln()method of the appropriate set type object as well, but usingparse_soln()is generally more efficient if a complete set of values is needed.
- display(mm, varargin)
Display the object.
mmCalled when semicolon is omitted at the command-line. Displays the details of the variables, constraints, costs included in the model.
- display_header(mm)
Display header, before each set type.
mm.display_header()
Called automatically by display, before displaying each set type.
Display footer, after each set type.
mm.display_footer()
Called automatically by display, after displaying each set type. By default, displays information about user data.
- display_soln(mm, varargin)
Display solution values.
mm.display_soln() mm.display_soln(set_type) mm.display_soln(set_type, name) mm.display_soln(set_type, name, idx) mm.display_soln(fid) mm.display_soln(fid, set_type) mm.display_soln(fid, set_type, name) mm.display_soln(fid, set_type, name, idx)
Displays the model solution, including values, bounds and shadow prices for variables, linear and quadratic constraints, values and shadow prices for nonlinear constraints, and individual cost components.
Results are displayed for all set types or those specified by
set_typeand for each named/indexed set or a specifiedname/idx.- Inputs:
set_type (char array or cell array) – one of the following, specifying the type of set:
'var'- variables'lin'- linear constraints'qcn'- quadratic constraints'nle'- nonlinear equality constraints'nli'- nonlinear inequality constraints'nlc'- nonlinear costs'qdc'- quadratic costs
or
a cell array of one or more of the above
or
''or'all'- indicating to display all
name (char array) – (optional) the name of the set
idx (cell array) – (optional) the indices of the set
Examples:
mm.display_soln('var'); mm.display_soln({'nle', 'nli'}); mm.display_soln('var', 'P'); mm.display_soln('lin', 'lin_con_1'); mm.display_soln('nle', 'nle_con_b', {2,3});
See also
parse_soln().