JuMP.AbstractConstraint
— Typeabstract type AbstractConstraint
An abstract base type for all constraint types. AbstractConstraint
s store the function and set directly, unlike ConstraintRef
s that are merely references to constraints stored in a model. AbstractConstraint
s do not need to be attached to a model.
JuMP.AbstractShape
— TypeAbstractShape
Abstract vectorizable shape. Given a flat vector form of an object of shape shape
, the original object can be obtained by reshape_vector
.
JuMP.AbstractVariable
— TypeAbstractVariable
Variable returned by build_variable
. It represents a variable that has not been added yet to any model. It can be added to a given model
with add_variable
.
JuMP.AbstractVariableRef
— TypeAbstractVariableRef
Variable returned by add_variable
. Affine (resp. quadratic) operations with variables of type V<:AbstractVariableRef
and coefficients of type T
create a GenericAffExpr{T,V}
(resp. GenericQuadExpr{T,V}
).
JuMP.AffExpr
— TypeAffExpr
Alias for GenericAffExpr{Float64,VariableRef}
, the specific GenericAffExpr
used by JuMP.
JuMP.BridgeableConstraint
— Typestruct BridgeableConstraint{C, B} <: AbstractConstraint
constraint::C
bridge_type::B
end
Constraint constraint
that can be bridged by the bridge of type bridge_type
. Adding this constraint to a model is equivalent to
add_bridge(model, bridge_type)
add_constraint(model, constraint)
Examples
Given a new scalar set type CustomSet
with a bridge CustomBridge
that can bridge F
-in-CustomSet
constraints, when the user does
model = Model()
@variable(model, x)
@constraint(model, x + 1 in CustomSet())
optimize!(model)
with an optimizer that does not support F
-in-CustomSet
constraints, the constraint will not be bridged unless he manually calls add_bridge(model, CustomBridge)
. In order to automatically add the CustomBridge
to any model to which an F
-in-CustomSet
is added, simply add the following method:
function JuMP.build_constraint(_error::Function, func::AbstractJuMPScalar,
set::CustomSet)
constraint = ScalarConstraint(func, set)
return JuMP.BridgeableConstraint(constraint, CustomBridge)
end
Note
JuMP extensions should extend JuMP.build_constraint
only if they also defined CustomSet
, for three reasons:
- It is problematic if multiple extensions overload the same JuMP method.
- A missing method will not inform the users that they forgot to load the extension module defining the
build_constraint
method. - Defining a method where neither the function nor any of the argument types are defined in the package is called type piracy and is discouraged in the Julia style guide.
JuMP.ConstraintNotOwned
— Typestruct ConstraintNotOwned{C <: ConstraintRef} <: Exception
constraint_ref::C
end
The constraint constraint_ref
was used in a model different to owner_model(constraint_ref)
.
JuMP.ConstraintRef
— TypeConstraintRef
Holds a reference to the model and the corresponding MOI.ConstraintIndex.
JuMP.GenericAffExpr
— Typemutable struct GenericAffExpr{CoefType,VarType} <: AbstractJuMPScalar
constant::CoefType
terms::OrderedDict{VarType,CoefType}
end
An expression type representing an affine expression of the form: $\sum a_i x_i + c$.
Fields
.constant
: the constantc
in the expression..terms
: anOrderedDict
, with keys ofVarType
and values ofCoefType
describing the sparse vectora
.
JuMP.GenericAffExpr
— MethodGenericAffExpr(constant::V, kv::Vararg{Pair{K,V},N}) where {K,V,N}
Create a GenericAffExpr
by passing a constant and pairs of additional arguments.
Examples
```jldoctest; setup=:(using JuMP; model = Model(); @variable(model, x)) julia> GenericAffExpr(1.0, x => 1.0) x + 1
JuMP.GenericAffExpr
— MethodGenericAffExpr(constant::V, kv::AbstractArray{Pair{K,V}}) where {K,V}
Create a GenericAffExpr
by passing a constant and a vector of pairs.
Examples
```jldoctest; setup=:(using JuMP; model = Model(); @variable(model, x)) julia> GenericAffExpr(1.0, [x => 1.0]) x + 1
JuMP.GenericQuadExpr
— Typemutable struct GenericQuadExpr{CoefType,VarType} <: AbstractJuMPScalar
aff::GenericAffExpr{CoefType,VarType}
terms::OrderedDict{UnorderedPair{VarType}, CoefType}
end
An expression type representing an quadratic expression of the form: $\sum q_{i,j} x_i x_j + \sum a_i x_i + c$.
Fields
.aff
: anGenericAffExpr
representing the affine portion of the expression..terms
: anOrderedDict
, with keys ofUnorderedPair{VarType}
and values ofCoefType
, describing the sparse list of termsq
.
JuMP.GenericQuadExpr
— MethodGenericQuadExpr(
aff::GenericAffExpr{V,K},
kv::AbstractArray{Pair{UnorderedPair{K},V}}
) where {K,V}
Create a GenericQuadExpr
by passing a GenericAffExpr
and a vector of (UnorderedPair
, coefficient) pairs.
Example
julia> GenericQuadExpr(GenericAffExpr(1.0, x => 2.0), [UnorderedPair(x, x) => 3.0])
3 x² + 2 x + 1
JuMP.Model
— TypeModel
A mathematical model of an optimization problem.
JuMP.Model
— MethodModel(optimizer_factory;
caching_mode::MOIU.CachingOptimizerMode=MOIU.AUTOMATIC,
bridge_constraints::Bool=true)
Return a new JuMP model with the provided optimizer and bridge settings. This function is equivalent to:
model = Model()
set_optimizer(model, optimizer_factory,
bridge_constraints=bridge_constraints)
return model
See set_optimizer
for the description of the optimizer_factory
and bridge_constraints
arguments.
Examples
The following creates a model with the optimizer set to Ipopt
:
model = Model(Ipopt.Optimizer)
JuMP.Model
— MethodModel(; caching_mode::MOIU.CachingOptimizerMode=MOIU.AUTOMATIC)
Return a new JuMP model without any optimizer; the model is stored the model in a cache. The mode of the CachingOptimizer
storing this cache is caching_mode
. Use set_optimizer
to set the optimizer before calling optimize!
.
JuMP.NoOptimizer
— Typestruct NoOptimizer <: Exception end
No optimizer is set. The optimizer can be provided to the Model
constructor or by calling set_optimizer
.
JuMP.OptimizeNotCalled
— Typestruct OptimizeNotCalled <: Exception end
A result attribute cannot be queried before optimize!
is called.
JuMP.PSDCone
— TypePSDCone
Positive semidefinite cone object that can be used to constrain a square matrix to be positive semidefinite in the @constraint
macro. If the matrix has type Symmetric
then the columns vectorization (the vector obtained by concatenating the columns) of its upper triangular part is constrained to belong to the MOI.PositiveSemidefiniteConeTriangle
set, otherwise its column vectorization is constrained to belong to the MOI.PositiveSemidefiniteConeSquare
set.
Examples
Consider the following example:
julia> model = Model();
julia> @variable(model, x)
x
julia> a = [ x 2x
2x x];
julia> b = [1 2
2 4];
julia> cref = @SDconstraint(model, a ⪰ b)
[x - 1 2 x - 2;
2 x - 2 x - 4 ] ∈ PSDCone()
julia> jump_function(constraint_object(cref))
4-element Array{GenericAffExpr{Float64,VariableRef},1}:
x - 1
2 x - 2
2 x - 2
x - 4
julia> moi_set(constraint_object(cref))
MathOptInterface.PositiveSemidefiniteConeSquare(2)
We see in the output of the last command that the matrix the vectorization of the matrix is constrained to belong to the PositiveSemidefiniteConeSquare
.
julia> using LinearAlgebra # For Symmetric
julia> cref = @constraint(model, Symmetric(a - b) in PSDCone())
[x - 1 2 x - 2;
2 x - 2 x - 4 ] ∈ PSDCone()
julia> jump_function(constraint_object(cref))
3-element Array{GenericAffExpr{Float64,VariableRef},1}:
x - 1
2 x - 2
x - 4
julia> moi_set(constraint_object(cref))
MathOptInterface.PositiveSemidefiniteConeTriangle(2)
As we see in the output of the last command, the vectorization of only the upper triangular part of the matrix is constrained to belong to the PositiveSemidefiniteConeSquare
.
JuMP.QuadExpr
— TypeQuadExpr
An alias for GenericQuadExpr{Float64,VariableRef}
, the specific GenericQuadExpr
used by JuMP.
JuMP.ReferenceMap
— TypeReferenceMap
Mapping between variable and constraint reference of a model and its copy. The reference of the copied model can be obtained by indexing the map with the reference of the corresponding reference of the original model.
JuMP.RotatedSecondOrderCone
— TypeRotatedSecondOrderCone
Rotated second order cone object that can be used to constrain the square of the euclidean norm of a vector x
to be less than or equal to $2tu$ where t
and u
are nonnegative scalars. This is a shortcut for the MOI.RotatedSecondOrderCone
.
Examples
The following constrains $\|(x-1, x-2)\|_2 \le 2tx$ and $t, x \ge 0$:
julia> model = Model();
julia> @variable(model, x)
x
julia> @variable(model, t)
t
julia> @constraint(model, [t, x, x-1, x-2] in RotatedSecondOrderCone())
[t, x, x - 1, x - 2] ∈ MathOptInterface.RotatedSecondOrderCone(4)
JuMP.SOS1
— TypeSOS1
SOS1 (Special Ordered Sets type 1) object than can be used to constrain a vector x
to a set where at most 1 variable can take a non-zero value, all others being at 0. The weights
, when specified, induce an ordering of the variables; as such, they should be unique values. The kth element in the set corresponds to the kth weight in weights
. See here for a description of SOS constraints and their potential uses. This is a shortcut for the MathOptInterface.SOS1
set.
JuMP.SOS2
— TypeSOS2
SOS1 (Special Ordered Sets type 2) object than can be used to constrain a vector x
to a set where at most 2 variables can take a non-zero value, all others being at 0. In addition, if two are non-zero these must be consecutive in their ordering. The weights
induce an ordering of the variables; as such, they should be unique values. The kth element in the set corresponds to the kth weight in weights
. See here for a description of SOS constraints and their potential uses. This is a shortcut for the MathOptInterface.SOS2
set.
JuMP.ScalarConstraint
— Typestruct ScalarConstraint
The data for a scalar constraint. The func
field containts a JuMP object representing the function and the set
field contains the MOI set. See also the documentation on JuMP's representation of constraints for more background.
JuMP.ScalarShape
— TypeScalarShape
Shape of scalar constraints.
JuMP.SecondOrderCone
— TypeSecondOrderCone
Second order cone object that can be used to constrain the euclidean norm of a vector x
to be less than or equal to a nonnegative scalar t
. This is a shortcut for the MOI.SecondOrderCone
.
Examples
The following constrains $\|(x-1, x-2)\|_2 \le t$ and $t \ge 0$:
julia> model = Model();
julia> @variable(model, x)
x
julia> @variable(model, t)
t
julia> @constraint(model, [t, x-1, x-2] in SecondOrderCone())
[t, x - 1, x - 2] ∈ MathOptInterface.SecondOrderCone(3)
JuMP.SensitivityReport
— TypeSensitivityReport
JuMP.SkewSymmetricMatrixShape
— TypeSkewSymmetricMatrixShape
Shape object for a skew symmetric square matrix of side_dimension
rows and columns. The vectorized form contains the entries of the upper-right triangular part of the matrix (without the diagonal) given column by column (or equivalently, the entries of the lower-left triangular part given row by row). The diagonal is zero.
JuMP.SkewSymmetricMatrixSpace
— TypeSkewSymmetricMatrixSpace()
Use in the @variable
macro to constrain a matrix of variables to be skew-symmetric.
Examples
@variable(model, Q[1:2, 1:2] in SkewSymmetricMatrixSpace())
JuMP.SquareMatrixShape
— TypeSquareMatrixShape
Shape object for a square matrix of side_dimension
rows and columns. The vectorized form contains the entries of the the matrix given column by column (or equivalently, the entries of the lower-left triangular part given row by row).
JuMP.SymmetricMatrixShape
— TypeSymmetricMatrixShape
Shape object for a symmetric square matrix of side_dimension
rows and columns. The vectorized form contains the entries of the upper-right triangular part of the matrix given column by column (or equivalently, the entries of the lower-left triangular part given row by row).
JuMP.UnorderedPair
— TypeUnorderedPair(a::T, b::T)
A wrapper type used by GenericQuadExpr
with fields .a
and .b
.
JuMP.VariableConstrainedOnCreation
— TypeVariablesConstrainedOnCreation <: AbstractVariable
Variable scalar_variables
constrained to belong to set
. Adding this variable can be understood as doing:
function JuMP.add_variable(model::Model, variable::JuMP.VariableConstrainedOnCreation, names)
var_ref = JuMP.add_variable(model, variable.scalar_variable, name)
JuMP.add_constraint(model, JuMP.VectorConstraint(var_ref, variable.set))
return var_ref
end
but adds the variables with MOI.add_constrained_variable(model, variable.set)
instead. See the MOI documentation for the difference between adding the variables with MOI.add_constrained_variable
and adding them with MOI.add_variable
and adding the constraint separately.
JuMP.VariableNotOwned
— Typestruct VariableNotOwned{V <: AbstractVariableRef} <: Exception
variable::V
end
The variable variable
was used in a model different to owner_model(variable)
.
JuMP.VariableRef
— TypeVariableRef <: AbstractVariableRef
Holds a reference to the model and the corresponding MOI.VariableIndex.
JuMP.VariablesConstrainedOnCreation
— TypeVariablesConstrainedOnCreation <: AbstractVariable
Vector of variables scalar_variables
constrained to belong to set
. Adding this variable can be thought as doing:
function JuMP.add_variable(model::Model, variable::JuMP.VariablesConstrainedOnCreation, names)
var_refs = JuMP.add_variable.(model, variable.scalar_variables,
JuMP.vectorize(names, variable.shape))
JuMP.add_constraint(model, JuMP.VectorConstraint(var_refs, variable.set))
return JuMP.reshape_vector(var_refs, variable.shape)
end
but adds the variables with MOI.add_constrained_variables(model, variable.set)
instead. See the MOI documentation for the difference between adding the variables with MOI.add_constrained_variables
and adding them with MOI.add_variables
and adding the constraint separately.
JuMP.VectorConstraint
— Typestruct VectorConstraint
The data for a vector constraint. The func
field containts a JuMP object representing the function and the set
field contains the MOI set. The shape
field contains an AbstractShape
matching the form in which the constraint was constructed (e.g., by using matrices or flat vectors). See also the documentation on JuMP's representation of constraints.
JuMP.VectorShape
— TypeVectorShape
Vector for which the vectorized form corresponds exactly to the vector given.
Base.copy
— Methodcopy(model::AbstractModel)
Return a copy of the model model
. It is similar to copy_model
except that it does not return the mapping between the references of model
and its copy.
Note
Model copy is not supported in DIRECT
mode, i.e. when a model is constructed using the direct_model
constructor instead of the Model
constructor. Moreover, independently on whether an optimizer was provided at model construction, the new model will have no optimizer, i.e., an optimizer will have to be provided to the new model in the optimize!
call.
Examples
In the following example, a model model
is constructed with a variable x
and a constraint cref
. It is then copied into a model new_model
with the new references assigned to x_new
and cref_new
.
model = Model()
@variable(model, x)
@constraint(model, cref, x == 2)
new_model = copy(model)
x_new = model[:x]
cref_new = model[:cref]
Base.empty!
— Methodempty!(model::Model) -> model
Empty the model, that is, remove all variables, constraints and model attributes but not optimizer attributes. Always return the argument.
Note: removes extensions data.
Base.getindex
— MethodBase.getindex(m::JuMP.AbstractModel, name::Symbol)
To allow easy accessing of JuMP Variables and Constraints via []
syntax. Returns the variable, or group of variables, or constraint, or group of constraints, of the given name which were added to the model. This errors if multiple variables or constraints share the same name.
Base.haskey
— Methodhaskey(model::AbstractModel, name::Symbol)
Determine whether the model has a mapping for a given name.
Base.read
— MethodBase.read(io::IO, ::Type{Model}; format::MOI.FileFormats.FileFormat)
Return a JuMP model read from io
in the format format
.
Base.setindex!
— MethodBase.setindex!(m::JuMP.AbstractModel, value, name::Symbol)
stores the object value
in the model m
using so that it can be accessed via getindex
. Can be called with []
syntax.
Base.write
— MethodBase.write(
io::IO,
model::Model;
format::MOI.FileFormats.FileFormat = MOI.FileFormats.FORMAT_MOF
)
Write the JuMP model model
to io
in the format format
.
JuMP.BinaryRef
— MethodBinaryRef(v::VariableRef)
Return a constraint reference to the constraint constrainting v
to be binary. Errors if one does not exist.
JuMP.FixRef
— MethodFixRef(v::VariableRef)
Return a constraint reference to the constraint fixing the value of v
. Errors if one does not exist.
JuMP.IntegerRef
— MethodIntegerRef(v::VariableRef)
Return a constraint reference to the constraint constrainting v
to be integer. Errors if one does not exist.
JuMP.LowerBoundRef
— MethodLowerBoundRef(v::VariableRef)
Return a constraint reference to the lower bound constraint of v
. Errors if one does not exist.
JuMP.UpperBoundRef
— MethodUpperBoundRef(v::VariableRef)
Return a constraint reference to the upper bound constraint of v
. Errors if one does not exist.
JuMP._add_kw_args
— Method_add_kw_args(call, kw_args)
Add the keyword arguments kw_args
to the function call expression call
, escaping the expressions. The elements of kw_args
should be expressions of the form :(key = value)
. The kw_args
vector can be extracted from the arguments of a macro with Containers._extract_kw_args
.
Examples
julia> call = :(f(1, a=2))
:(f(1, a=2))
julia> JuMP._add_kw_args(call, [:(b=3), :(c=4)])
julia> call
:(f(1, a=2, $(Expr(:escape, :(b = 3))), $(Expr(:escape, :(c = 4)))))
JuMP._compute_rhs_range
— Method_compute_rhs_range(d_B, x_B, l_B, u_B, atol)
Assume we start with the optimal solution x_old
, we want to compute a step size t
in a direction d
such that x_new = x_old + t * d
is still represented by the same optimal basis. This can be computed a la primal simplex where we use an artificial entering variable.
A * x_new = A * (x_old + t * d)
= A * x_old + t * A * d
= 0 + t * A * d # Since A * x_old = 0
=> A * d = 0
=> B * d_B + N * d_N = 0
=> d_B = B \ -(N * d_N)
Note we only have to compute the basic component of the direction vector, because d_N
is just zeros with a 1
in the component associated with the artificial entering variable. Therefore, all that remains is to compute the associated column of N
.
If we are increasing the bounds associated with the i
th decision variable, then our artificial entering variable is a duplicate of the i
th variable, and N * d_N = A[:, i]
.
If we are increasing the bounds associated with the i
th affine constraint, then our artificial entering variable is a duplicate of the slack variable associated with the i
th constraint, i.e., a -1
in the i
th row and zeros everywhere else.
In either case:
d_B = -(B \ A[:, i])
Now, having computed a direction such that x_new = x_old + t * d
. By ensuring that A * d = 0
, we maintained structural feasibility. Now we need to compute bounds on t
such that x_new
maintains bound feasibility. That is, compute bounds on t such that:
l_B[j] <= x_B[j] + t * d_B[j] <= u_B[j].
JuMP._constraint_macro
— Method_constraint_macro(
args, macro_name::Symbol, parsefun::Function, source::LineNumberNode
)
Returns the code for the macro @constraint_like args...
of syntax
@constraint_like con # Single constraint
@constraint_like ref con # group of constraints
where @constraint_like
is either @constraint
or @SDconstraint
.
The expression con
is parsed by parsefun
which returns a build_constraint
call code that, when executed, returns an AbstractConstraint
. The macro keyword arguments (except the container
keyword argument which is used to determine the container type) are added to the build_constraint
call. The returned value of this call is passed to add_constraint
which returns a constraint reference.
source
is a LineNumberNode
that should refer to the line that the macro was called from in the user's code. One way of generating this is via the hidden variable __source__
.
JuMP._fill_vaf!
— Method_fill_vaf!(terms::Vector{<:MOI.VectorAffineTerm}, offset::Int, oi::Int,
aff::AbstractJuMPScalar)
Fills the vectors terms at indices starting at offset+1
with the affine terms of aff
. The output index for all terms is oi
. Return the index of the last term added.
JuMP._fill_vqf!
— Method_fill_vqf!(terms::Vector{<:MOI.VectorQuadraticTerm}, offset::Int, oi::Int,
quad::AbstractJuMPScalar)
Fills the vectors terms at indices starting at offset+1
with the quadratic terms of quad
. The output index for all terms is oi
. Return the index of the last term added.
JuMP._finalize_macro
— Method_finalize_macro(model, code, source::LineNumberNode)
Wraps the code
generated by a macro in a code block with the first argument as source
, the LineNumberNode
of where the macro was called from in the user's code. This results in better stacktraces in error messages.
In addition, it checks that model
is a valid AbstractModel
.
Note: assumes model
is already escaped.
JuMP._is_lp
— Method_is_lp(model::Model)
Return true
if model
is a linear program.
JuMP._macro_assign_and_return
— Method_macro_assign_and_return(code, variable, name;
model_for_registering=nothing)
Return code
which returns the value of variable
and then assigns variable
to name
. If model_for_registering
is given, the generated code assigns the resulting object to the model dictionary.
JuMP._moi_quadratic_term
— Method_moi_quadratic_term(t::Tuple)
Return the MOI.ScalarQuadraticTerm for the quadratic term t
, element of the quad_terms
iterator. Note that the VariableRef
s are transformed into MOI.VariableIndex
s hence the owner model information is lost.
JuMP._moi_sense
— Method_moi_sense(_error::Function, sense)
Return an expression whose value is an MOI.OptimizationSense
corresponding to sense
. Sense is either the symbol :Min
or :Max
, corresponding respectively to MOI.MIN_SENSE
and MOI.MAX_SENSE
or it is another symbol, which should be the name of a variable or expression whose value is an MOI.OptimizationSense
. In the last case, the expression throws an error using the _error
function in case the value is not an MOI.OptimizationSense
.
JuMP._nlp_objective_function
— Method_nlp_objective_function(model::Model)
Returns the nonlinear objective function or nothing
if no nonlinear objective function is set.
JuMP._standard_form_matrix
— Method_standard_form_matrix(model::Model)
Given a problem:
r_l <= Ax <= r_u
c_l <= x <= c_u
Return the standard form:
[A -I] [x, y] = 0
[c_l, r_l] <= [x, y] <= [c_u, r_u]
columns
maps the variable references to column indices.
JuMP._std_basis_status
— MethodReturns the basis status of all variables of the problem in standard form, c.f. _std_matrix(model)
.
JuMP._std_matrix
— MethodBuilds the standard form constraint matrix, variable bounds, and a vector of constraint reference, one for each row. If à is the current constraint matrix, and the corresponding feasible set is of the form s.t. RowL <= Ãx <= RowU, VarL <= x <= VarU. (Equality constraint is interpreted as, e.g., RowLi == RowUi, and single sided constraints with an infinite value in the free directions) Then the function returns a tuple with A = [à -I] varlower = [VarL, RowL] varupper = [VarU, RowU] affineconstraints::Vector{ConstraintRef} - references corresponding to RowL <= Ãx <= RowU This represents the LP problem feasible set of the form s.t. Ax == 0 varlower <= x <= var_upper
JuMP._std_primal_solution
— MethodReturns the optimal primal values for the problem in standard form, c.f. _std_matrix(model)
.
JuMP._std_reduced_costs
— MethodReturns the optimal reduced costs for the variables of the problem in standard form, c.f. _std_matrix(model)
JuMP.add_bridge
— Method add_bridge(model::Model,
BridgeType::Type{<:MOI.Bridges.AbstractBridge})
Add BridgeType
to the list of bridges that can be used to transform unsupported constraints into an equivalent formulation using only constraints supported by the optimizer.
JuMP.add_constraint
— Functionadd_constraint(model::Model, con::AbstractConstraint, name::String="")
Add a constraint con
to Model model
and sets its name.
JuMP.add_to_expression!
— Functionadd_to_expression!(expression, terms...)
Updates expression
in place to expression + (*)(terms...)
. This is typically much more efficient than expression += (*)(terms...)
. For example, add_to_expression!(expression, a, b)
produces the same result as expression += a*b
, and add_to_expression!(expression, a)
produces the same result as expression += a
.
Only a few methods are defined, mostly for internal use, and only for the cases when (1) they can be implemented efficiently and (2) expression
is capable of storing the result. For example, add_to_expression!(::AffExpr, ::VariableRef, ::VariableRef)
is not defined because a GenericAffExpr
cannot store the product of two variables.
JuMP.add_to_function_constant
— Methodadd_to_function_constant(constraint::ConstraintRef, value)
Add value
to the function constant term.
Note that for scalar constraints, JuMP will aggregate all constant terms onto the right-hand side of the constraint so instead of modifying the function, the set will be translated by -value
. For example, given a constraint 2x <= 3
, add_to_function_constant(c, 4)
will modify it to 2x <= -1
.
Examples
For scalar constraints, the set is translated by -value
:
julia> @constraint(model, con, 0 <= 2x - 1 <= 2)
con : 2 x ∈ [1.0, 3.0]
julia> add_to_function_constant(con, 4)
julia> con
con : 2 x ∈ [-3.0, -1.0]
For vector constraints, the constant is added to the function:
julia> @constraint(model, con, [x + y, x, y] in SecondOrderCone())
con : [x + y, x, y] ∈ MathOptInterface.SecondOrderCone(3)
julia> add_to_function_constant(con, [1, 2, 2])
julia> con
con : [x + y + 1, x + 2, y + 2] ∈ MathOptInterface.SecondOrderCone(3)
JuMP.add_variable
— Functionadd_variable(m::Model, v::AbstractVariable, name::String="")
Add a variable v
to Model m
and sets its name.
JuMP.all_constraints
— Methodall_constraints(model::Model, function_type, set_type)::Vector{<:ConstraintRef}
Return a list of all constraints currently in the model where the function has type function_type
and the set has type set_type
. The constraints are ordered by creation time.
See also list_of_constraint_types
and num_constraints
.
Example
julia> model = Model();
julia> @variable(model, x >= 0, Bin);
julia> @constraint(model, 2x <= 1);
julia> all_constraints(model, VariableRef, MOI.GreaterThan{Float64})
1-element Array{ConstraintRef{Model,MathOptInterface.ConstraintIndex{MathOptInterface.SingleVariable,MathOptInterface.GreaterThan{Float64}},ScalarShape},1}:
x ≥ 0.0
julia> all_constraints(model, VariableRef, MOI.ZeroOne)
1-element Array{ConstraintRef{Model,MathOptInterface.ConstraintIndex{MathOptInterface.SingleVariable,MathOptInterface.ZeroOne},ScalarShape},1}:
x binary
julia> all_constraints(model, AffExpr, MOI.LessThan{Float64})
1-element Array{ConstraintRef{Model,MathOptInterface.ConstraintIndex{MathOptInterface.ScalarAffineFunction{Float64},MathOptInterface.LessThan{Float64}},ScalarShape},1}:
2 x ≤ 1.0
JuMP.all_variables
— Methodall_variables(model::Model)::Vector{VariableRef}
Returns a list of all variables currently in the model. The variables are ordered by creation time.
Example
model = Model()
@variable(model, x)
@variable(model, y)
all_variables(model)
# output
2-element Array{VariableRef,1}:
x
y
JuMP.backend
— Methodbackend(model::Model)
Return the lower-level MathOptInterface model that sits underneath JuMP. This model depends on which operating mode JuMP is in (manual, automatic, or direct), and whether there are any bridges in the model.
If JuMP is in direct mode (i.e., the model was created using direct_model
), the backend with be the optimizer passed to direct_model
. If JuMP is in manual or automatic mode, the backend is a MOI.Utilities.CachingOptimizer
.
This function should only be used by advanced users looking to access low-level MathOptInterface or solver-specific functionality.
JuMP.barrier_iterations
— Methodbarrier_iterations(model::Model)
Gets the cumulative number of barrier iterations during the most recent optimization.
Solvers must implement MOI.BarrierIterations()
to use this function.
JuMP.bridge_constraints
— Methodbridge_constraints(model::Model)
When in direct mode, return false
. When in manual or automatic mode, return a Bool
indicating whether the optimizer is set and unsupported constraints are automatically bridged to equivalent supported constraints when an appropriate transformation is available.
JuMP.build_constraint
— Methodbuild_constraint(_error::Function,
Q::AbstractMatrix{<:AbstractJuMPScalar},
::PSDCone)
Return a VectorConstraint
of shape SquareMatrixShape
constraining the matrix Q
to be symmetric and positive semidefinite.
This function is used by the @constraint
and @SDconstraint
macros as follows:
@constraint(model, Q in PSDCone())
@SDconstraint(model, P ⪰ Q)
The @constraint
call above is usually used when the entries of Q
are affine or quadratic expressions, but it can also be used when the entries are variables to get the reference of the semidefinite constraint, e.g.,
@variable model Q[1:2,1:2]
# The type of `Q` is `Matrix{VariableRef}`
var_psd = @constraint model Q in PSDCone()
# The `var_psd` variable contains a reference to the constraint
JuMP.build_constraint
— Methodbuild_constraint(_error::Function, Q::Symmetric{V, M},
::PSDCone) where {V <: AbstractJuMPScalar,
M <: AbstractMatrix{V}}
Return a VectorConstraint
of shape SymmetricMatrixShape
constraining the matrix Q
to be positive semidefinite.
This function is used by the @constraint
macros as follows:
@constraint(model, Symmetric(Q) in PSDCone())
The form above is usually used when the entries of Q
are affine or quadratic expressions, but it can also be used when the entries are variables to get the reference of the semidefinite constraint, e.g.,
@variable model Q[1:2,1:2] Symmetric
# The type of `Q` is `Symmetric{VariableRef, Matrix{VariableRef}}`
var_psd = @constraint model Q in PSDCone()
# The `var_psd` variable contains a reference to the constraint
JuMP.build_variable
— Methodbuild_constraint(_error::Function, variables, ::PSDCone)
Return a VariablesConstrainedOnCreation
of shape SymmetricMatrixShape
constraining the variables to be positive semidefinite.
This function is used by the @variable
macro as follows:
@variable(model, Q[1:2, 1:2], PSD)
JuMP.build_variable
— Methodbuild_variable(_error::Function, variables, ::SkewSymmetricMatrixSpace)
Return a VariablesConstrainedOnCreation
of shape SkewSymmetricMatrixShape
creating variables in MOI.Reals
, i.e. "free" variables unless they are constrained after their creation.
This function is used by the @variable
macro as follows:
@variable(model, Q[1:2, 1:2] in SkewSymmetricMatrixSpace())
JuMP.build_variable
— Methodbuild_constraint(_error::Function, variables, ::SymMatrixSpace)
Return a VariablesConstrainedOnCreation
of shape SymmetricMatrixShape
creating variables in MOI.Reals
, i.e. "free" variables unless they are constrained after their creation.
This function is used by the @variable
macro as follows:
@variable(model, Q[1:2, 1:2], Symmetric)
JuMP.callback_node_status
— Methodcallback_node_status(cb_data, model::Model)
Return an MOI.CallbackNodeStatusCode
enum, indicating if the current primal solution available from callback_value
is integer feasible.
JuMP.callback_value
— Methodcallback_value(cb_data, expr::Union{GenericAffExpr, GenericQuadExpr})
Return the primal solution of an affine or quadratic expression inside a callback by getting the value for each variable appearing in the expression.
cb_data
is the argument to the callback function, and the type is dependent on the solver.
JuMP.callback_value
— Methodcallback_value(cb_data, x::VariableRef)
Return the primal solution of a variable inside a callback.
cb_data
is the argument to the callback function, and the type is dependent on the solver.
JuMP.check_belongs_to_model
— Functioncheck_belongs_to_model(func::AbstractJuMPScalar, model::AbstractModel)
Throw VariableNotOwned
if the owner_model
of one of the variables of the function func
is not model
.
check_belongs_to_model(constraint::AbstractConstraint, model::AbstractModel)
Throw VariableNotOwned
if the owner_model
of one of the variables of the constraint constraint
is not model
.
JuMP.check_belongs_to_model
— Methodcheck_belongs_to_model(con_ref::ConstraintRef, model::AbstractModel)
Throw ConstraintNotOwned
if owner_model(con_ref)
is not model
.
JuMP.compute_conflict!
— Methodcompute_conflict!(model::Model)
Compute a conflict if the model is infeasible. If an optimizer has not been set yet (see set_optimizer
), a NoOptimizer
error is thrown.
The status of the conflict can be checked with the MOI.ConflictStatus
model attribute. Then, the status for each constraint can be queried with the MOI.ConstraintConflictStatus
attribute.
JuMP.constant
— Methodconstant(aff::GenericAffExpr{C, V})::C
Return the constant of the affine expression.
JuMP.constant
— Methodconstant(aff::GenericQuadExpr{C, V})::C
Return the constant of the quadratic expression.
JuMP.constraint_by_name
— Functionconstraint_by_name(model::AbstractModel,
name::String)::Union{ConstraintRef, Nothing}
Returns the reference of the constraint with name attribute name
or Nothing
if no constraint has this name attribute. Throws an error if several constraints have name
as their name attribute.
constraint_by_name(model::AbstractModel,
name::String,
F::Type{<:Union{AbstractJuMPScalar,
Vector{<:AbstractJuMPScalar},
MOI.AbstactFunction}},
S::Type{<:MOI.AbstractSet})::Union{ConstraintRef, Nothing}
Similar to the method above, except that it throws an error if the constraint is not an F
-in-S
contraint where F
is either the JuMP or MOI type of the function, and S
is the MOI type of the set. This method is recommended if you know the type of the function and set since its returned type can be inferred while for the method above (i.e. without F
and S
), the exact return type of the constraint index cannot be inferred.
julia> using JuMP
julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.
julia> @variable(model, x)
x
julia> @constraint(model, con, x^2 == 1)
con : x² = 1.0
julia> constraint_by_name(model, "kon")
julia> constraint_by_name(model, "con")
con : x² = 1.0
julia> constraint_by_name(model, "con", AffExpr, MOI.EqualTo{Float64})
julia> constraint_by_name(model, "con", QuadExpr, MOI.EqualTo{Float64})
con : x² = 1.0
JuMP.constraint_object
— Functionconstraint_object(con_ref::ConstraintRef)
Return the underlying constraint data for the constraint referenced by ref
.
JuMP.constraints_string
— Methodconstraints_string(print_mode, model::AbstractModel)::Vector{String}
Return a list of String
s describing each constraint of the model.
JuMP.copy_extension_data
— Functioncopy_extension_data(data, new_model::AbstractModel, model::AbstractModel)
Return a copy of the extension data data
of the model model
to the extension data of the new model new_model
. A method should be added for any JuMP extension storing data in the ext
field.
JuMP.copy_model
— Methodcopy_model(model::Model)
Return a copy of the model model
and a ReferenceMap
that can be used to obtain the variable and constraint reference of the new model corresponding to a given model
's reference. A Base.copy(::AbstractModel)
method has also been implemented, it is similar to copy_model
but does not return the reference map.
Note
Model copy is not supported in DIRECT
mode, i.e. when a model is constructed using the direct_model
constructor instead of the Model
constructor. Moreover, independently on whether an optimizer was provided at model construction, the new model will have no optimizer, i.e., an optimizer will have to be provided to the new model in the optimize!
call.
Examples
In the following example, a model model
is constructed with a variable x
and a constraint cref
. It is then copied into a model new_model
with the new references assigned to x_new
and cref_new
.
model = Model()
@variable(model, x)
@constraint(model, cref, x == 2)
new_model, reference_map = copy_model(model)
x_new = reference_map[x]
cref_new = reference_map[cref]
JuMP.delete
— Methoddelete(model::Model, variable_refs::Vector{VariableRef})
Delete the variables associated with variable_refs
from the model model
. Solvers may implement methods for deleting multiple variables that are more efficient than repeatedly calling the single variable delete method.
See also: unregister
JuMP.delete
— Methoddelete(model::Model, con_refs::Vector{<:ConstraintRef})
Delete the constraints associated with con_refs
from the model model
. Solvers may implement specialized methods for deleting multiple constraints of the same concrete type, i.e., when isconcretetype(eltype(con_refs))
. These may be more efficient than repeatedly calling the single constraint delete method.
See also: unregister
JuMP.delete
— Methoddelete(model::Model, con_ref::ConstraintRef)
Delete the constraint associated with constraint_ref
from the model model
.
See also: unregister
JuMP.delete
— Methoddelete(model::Model, variable_ref::VariableRef)
Delete the variable associated with variable_ref
from the model model
.
See also: unregister
JuMP.delete_lower_bound
— Methoddelete_lower_bound(v::VariableRef)
Delete the lower bound constraint of a variable.
JuMP.delete_upper_bound
— Methoddelete_upper_bound(v::VariableRef)
Delete the upper bound constraint of a variable.
JuMP.direct_model
— Methoddirect_model(backend::MOI.ModelLike)
Return a new JuMP model using backend
to store the model and solve it. As opposed to the Model
constructor, no cache of the model is stored outside of backend
and no bridges are automatically applied to backend
. The absence of cache reduces the memory footprint but it is important to bear in mind the following implications of creating models using this direct mode:
- When
backend
does not support an operation, such as modifying constraints or adding variables/constraints after solving, an error is thrown. For models created using theModel
constructor, such situations can be dealt with by storing the modifications in a cache and loading them into the optimizer whenoptimize!
is called. - No constraint bridging is supported by default.
- The optimizer used cannot be changed the model is constructed.
- The model created cannot be copied.
JuMP.drop_zeros!
— Methoddrop_zeros!(expr::GenericAffExpr)
Remove terms in the affine expression with 0
coefficients.
JuMP.drop_zeros!
— Methoddrop_zeros!(expr::GenericQuadExpr)
Remove terms in the quadratic expression with 0
coefficients.
JuMP.dual
— Methoddual(con_ref::ConstraintRef; result::Int = 1)
Return the dual value of constraint con_ref
associated with result index result
of the most-recent solution returned by the solver.
Use has_dual
to check if a result exists before asking for values.
See also: result_count
, shadow_price
.
JuMP.dual_objective_value
— Methoddual_objective_value(model::Model; result::Int = 1)
Return the value of the objective of the dual problem associated with result index result
of the most-recent solution returned by the solver.
Throws MOI.UnsupportedAttribute{MOI.DualObjectiveValue}
if the solver does not support this attribute.
See also: result_count
.
JuMP.dual_shape
— Methoddual_shape(shape::AbstractShape)::AbstractShape
Returns the shape of the dual space of the space of objects of shape shape
. By default, the dual_shape
of a shape is itself. See the examples section below for an example for which this is not the case.
Examples
Consider polynomial constraints for which the dual is moment constraints and moment constraints for which the dual is polynomial constraints. Shapes for polynomials can be defined as follows:
struct Polynomial
coefficients::Vector{Float64}
monomials::Vector{Monomial}
end
struct PolynomialShape <: AbstractShape
monomials::Vector{Monomial}
end
JuMP.reshape_vector(x::Vector, shape::PolynomialShape) = Polynomial(x, shape.monomials)
and a shape for moments can be defined as follows:
struct Moments
coefficients::Vector{Float64}
monomials::Vector{Monomial}
end
struct MomentsShape <: AbstractShape
monomials::Vector{Monomial}
end
JuMP.reshape_vector(x::Vector, shape::MomentsShape) = Moments(x, shape.monomials)
Then dual_shape
allows the definition of the shape of the dual of polynomial and moment constraints:
dual_shape(shape::PolynomialShape) = MomentsShape(shape.monomials)
dual_shape(shape::MomentsShape) = PolynomialShape(shape.monomials)
JuMP.dual_start_value
— Methoddual_start_value(con_ref::ConstraintRef)
Return the dual start value (MOI attribute ConstraintDualStart
) of the constraint con_ref
.
Note: If no dual start value has been set, dual_start_value
will return nothing
.
See also set_dual_start_value
.
JuMP.dual_status
— Methoddual_status(model::Model; result::Int = 1)
Return the status of the most recent dual solution of the solver (i.e., the MathOptInterface model attribute DualStatus
) associated with the result index result
.
See also: result_count
.
JuMP.error_if_direct_mode
— Methoderror_if_direct_mode(model::Model, func::Symbol)
Errors if model
is in direct mode during a call from the function named func
.
Used internally within JuMP, or by JuMP extensions who do not want to support models in direct mode.
JuMP.fix
— Methodfix(v::VariableRef, value::Number; force::Bool = false)
Fix a variable to a value. Update the fixing constraint if one exists, otherwise create a new one. See also unfix
.
If the variable already has variable bounds and force=false
, calling fix
will throw an error. If force=true
, existing variable bounds will be deleted, and the fixing constraint will be added. Note a variable will have no bounds after a call to unfix
.
JuMP.fix_value
— Methodfix_value(v::VariableRef)
Return the value to which a variable is fixed. Error if one does not exist. See also is_fixed
.
JuMP.function_string
— Functionfunction_string(print_mode::Type{<:JuMP.PrintMode},
func::Union{JuMP.AbstractJuMPScalar,
Vector{<:JuMP.AbstractJuMPScalar}})
Return a String
representing the function func
using print mode print_mode
.
JuMP.function_string
— Methodfunction_string(print_mode::{<:JuMP.PrintMode},
constraint::JuMP.AbstractConstraint)
Return a String
representing the function of the constraint constraint
using print mode print_mode
.
JuMP.get_optimizer_attribute
— Methodget_optimizer_attribute(
model::Model, attr::MOI.AbstractOptimizerAttribute
)
Return the value of the solver-specific attribute attr
in model
.
Example
get_optimizer_attribute(model, MOI.Silent())
See also: set_optimizer_attribute
, set_optimizer_attributes
.
JuMP.get_optimizer_attribute
— Methodget_optimizer_attribute(model, name::String)
Return the value associated with the solver-specific attribute named name
.
Note that this is equivalent to get_optimizer_attribute(model, MOI.RawParameter(name))
.
Example
get_optimizer_attribute(model, "SolverSpecificAttributeName")
See also: set_optimizer_attribute
, set_optimizer_attributes
.
JuMP.has_duals
— Methodhas_duals(model::Model; result::Int = 1)
Return true
if the solver has a dual solution in result index result
available to query, otherwise return false
.
See also dual
, shadow_price
, and result_count
.
JuMP.has_lower_bound
— Methodhas_lower_bound(v::VariableRef)
Return true
if v
has a lower bound. If true
, the lower bound can be queried with lower_bound
. See also LowerBoundRef
.
JuMP.has_upper_bound
— Methodhas_upper_bound(v::VariableRef)
Return true
if v
has a upper bound. If true
, the upper bound can be queried with upper_bound
. See also UpperBoundRef
.
JuMP.has_values
— Methodhas_values(model::Model; result::Int = 1)
Return true
if the solver has a primal solution in result index result
available to query, otherwise return false
.
See also value
and result_count
.
JuMP.in_set_string
— Methodin_set_string(print_mode::Type{<:JuMP.PrintMode},
constraint::JuMP.AbstractConstraint)
Return a String
representing the membership to the set of the constraint constraint
using print mode print_mode
.
JuMP.in_set_string
— Methodin_set_string(print_mode::Type{<:JuMP.PrintMode},
set::Union{PSDCone, MOI.AbstractSet})
Return a String
representing the membership to the set set
using print mode print_mode
.
JuMP.index
— Methodindex(cr::ConstraintRef)::MOI.ConstraintIndex
Return the index of the constraint that corresponds to cr
in the MOI backend.
JuMP.index
— Methodindex(v::VariableRef)::MOI.VariableIndex
Return the index of the variable that corresponds to v
in the MOI backend.
JuMP.is_binary
— Methodis_binary(v::VariableRef)
Return true
if v
is constrained to be binary. See also BinaryRef
.
JuMP.is_fixed
— MethodJuMP.is_integer
— Methodis_integer(v::VariableRef)
Return true
if v
is constrained to be integer. See also IntegerRef
.
JuMP.is_valid
— Methodis_valid(model::Model, con_ref::ConstraintRef{Model})
Return true
if constraint_ref
refers to a valid constraint in model
.
JuMP.is_valid
— Methodis_valid(model::Model, variable_ref::VariableRef)
Return true
if variable
refers to a valid variable in model
.
JuMP.isequal_canonical
— Methodisequal_canonical(
aff::GenericAffExpr{C,V},
other::GenericAffExpr{C,V}
) where {C,V}
Return true
if aff
is equal to other
after dropping zeros and disregarding the order. Mainly useful for testing.
JuMP.jump_function
— Functionjump_function(x)
Given an MathOptInterface object x
, return the JuMP equivalent.
See also: moi_function
.
JuMP.jump_function
— Methodjump_function(constraint::AbstractConstraint)
Return the function of the constraint constraint
in the function-in-set form as a AbstractJuMPScalar
or Vector{AbstractJuMPScalar}
.
JuMP.jump_function_type
— Functionjump_function_type(::Type{T}) where {T}
Given an MathOptInterface object type T
, return the JuMP equivalent.
See also: moi_function_type
.
JuMP.linear_terms
— Methodlinear_terms(aff::GenericAffExpr{C, V})
Provides an iterator over coefficient-variable tuples (a_i::C, x_i::V)
in the linear part of the affine expression.
JuMP.linear_terms
— Methodlinear_terms(quad::GenericQuadExpr{C, V})
Provides an iterator over tuples (coefficient::C, variable::V)
in the linear part of the quadratic expression.
JuMP.list_of_constraint_types
— Methodlist_of_constraint_types(model::Model)::Vector{Tuple{DataType, DataType}}
Return a list of tuples of the form (F, S)
where F
is a JuMP function type and S
is an MOI set type such that all_constraints(model, F, S)
returns a nonempty list.
Example
julia> model = Model();
julia> @variable(model, x >= 0, Bin);
julia> @constraint(model, 2x <= 1);
julia> list_of_constraint_types(model)
3-element Array{Tuple{DataType,DataType},1}:
(GenericAffExpr{Float64,VariableRef}, MathOptInterface.LessThan{Float64})
(VariableRef, MathOptInterface.GreaterThan{Float64})
(VariableRef, MathOptInterface.ZeroOne)
JuMP.lower_bound
— Methodlower_bound(v::VariableRef)
Return the lower bound of a variable. Error if one does not exist. See also has_lower_bound
.
JuMP.lp_objective_perturbation_range
— Methodlp_objective_perturbation_range(var::VariableRef;
optimality_tolerance::Float64)
::Tuple{Float64, Float64}
Gives the range by which the cost coefficient can change and the current LP basis remains optimal, i.e., the reduced costs remain valid.
Notes
- The range denotes valid changes, Δ ∈ [l, u], for which cost[var] += Δ do not violate the current optimality conditions.
optimality_tolerance
is the dual feasibility tolerance, this should preferably match the tolerance used by the solver. The defualt tolerance should however apply in most situations (c.f. "Computational Techniques of the Simplex Method" by István Maros, section 9.3.4).
JuMP.lp_rhs_perturbation_range
— Methodlp_rhs_perturbation_range(constraint::ConstraintRef;
feasibility_tolerance::Float64)
::Tuple{Float64, Float64}
Gives the range by which the rhs coefficient can change and the current LP basis remains feasible, i.e., where the shadow prices apply.
Notes
- The rhs coefficient is the value right of the relation, i.e., b for the constraint when of the form a*x □ b, where □ is ≤, =, or ≥.
- The range denotes valid changes, e.g., for a*x <= b + Δ, the LP basis remains feasible for all Δ ∈ [l, u].
feasibility_tolerance
is the primal feasibility tolerance, this should preferably match the tolerance used by the solver. The default tolerance should however apply in most situations (c.f. "Computational Techniques of the Simplex Method" by István Maros, section 9.3.4).
JuMP.lp_sensitivity_report
— Methodlp_sensitivity_report(model::Model; atol::Float64 = 1e-8)::SensitivityReport
Given a linear program model
with a current optimal basis, return a SensitivityReport
object, which maps:
- Every variable reference to a tuple
(d_lo, d_hi)::Tuple{Float64,Float64}
, explaining how much the objective coefficient of the corresponding variable can change by, such that the original basis remains optimal. - Every constraint reference to a tuple
(d_lo, d_hi)::Tuple{Float64,Float64}
, explaining how much the right-hand side of the corresponding constraint can change by, such that the basis remains optimal.
Both tuples are relative, rather than absolute. So given a objective coefficient of 1.0
and a tuple (-0.5, 0.5)
, the objective coefficient can range between 1.0 - 0.5
an 1.0 + 0.5
.
atol
is the primal/dual optimality tolerance, and should match the tolerance of the solver used to compute the basis.
Note: interval constraints are NOT supported.
Example
model = Model(GLPK.Optimizer)
@variable(model, -1 <= x <= 2)
@objective(model, Min, x)
optimize!(model)
report = lp_sensitivity_report(model; atol = 1e-7)
dx_lo, dx_hi = report[x]
println(
"The objective coefficient of `x` can decrease by $dx_lo or " *
"increase by $dx_hi."
)
c = LowerBoundRef(x)
dRHS_lo, dRHS_hi = report[c]
println(
"The lower bound of `x` can decrease by $dRHS_lo or increase " *
"by $dRHS_hi."
)
JuMP.map_coefficients
— Methodmap_coefficients(f::Function, a::GenericAffExpr)
Apply f
to the coefficients and constant term of an GenericAffExpr
a
and return a new expression.
See also: map_coefficients_inplace!
Example
julia> a = GenericAffExpr(1.0, x => 1.0)
x + 1
julia> map_coefficients(c -> 2 * c, a)
2 x + 2
julia> a
x + 1
JuMP.map_coefficients
— Methodmap_coefficients(f::Function, a::GenericQuadExpr)
Apply f
to the coefficients and constant term of an GenericQuadExpr
a
and return a new expression.
See also: map_coefficients_inplace!
Example
julia> a = @expression(model, x^2 + x + 1)
x² + x + 1
julia> map_coefficients(c -> 2 * c, a)
2 x² + 2 x + 2
julia> a
x² + x + 1
JuMP.map_coefficients_inplace!
— Methodmap_coefficients_inplace!(f::Function, a::GenericAffExpr)
Apply f
to the coefficients and constant term of an GenericAffExpr
a
and update them in-place.
See also: map_coefficients
Example
julia> a = GenericAffExpr(1.0, x => 1.0)
x + 1
julia> map_coefficients_inplace!(c -> 2 * c, a)
2 x + 2
julia> a
2 x + 2
JuMP.map_coefficients_inplace!
— Methodmap_coefficients_inplace!(f::Function, a::GenericQuadExpr)
Apply f
to the coefficients and constant term of an GenericQuadExpr
a
and update them in-place.
See also: map_coefficients
Example
julia> a = @expression(model, x^2 + x + 1)
x² + x + 1
julia> map_coefficients_inplace!(c -> 2 * c, a)
2 x² + 2 x + 2
julia> a
2 x² + 2 x + 2
JuMP.mode
— Methodmode(model::Model)
Return mode (DIRECT, AUTOMATIC, MANUAL) of model.
JuMP.moi_function
— Functionmoi_function(x)
Given a JuMP object x
, return the MathOptInterface equivalent.
See also: jump_function
.
JuMP.moi_function
— Methodmoi_function(constraint::AbstractConstraint)
Return the function of the constraint constraint
in the function-in-set form as a MathOptInterface.AbstractFunction
.
JuMP.moi_function_type
— Functionmoi_function_type(::Type{T}) where {T}
Given a JuMP object type T
, return the MathOptInterface equivalent.
See also: jump_function_type
.
JuMP.moi_set
— Methodmoi_set(constraint::AbstractConstraint)
Return the set of the constraint constraint
in the function-in-set form as a MathOptInterface.AbstractSet
.
moi_set(s::AbstractVectorSet, dim::Int)
Returns the MOI set of dimension dim
corresponding to the JuMP set s
.
JuMP.name
— Methodname(con_ref::ConstraintRef)
Get a constraint's name attribute.
JuMP.name
— Methodname(v::VariableRef)::String
Get a variable's name attribute.
JuMP.node_count
— Methodnode_count(model::Model)
Gets the total number of branch-and-bound nodes explored during the most recent optimization in a Mixed Integer Program.
Solvers must implement MOI.NodeCount()
to use this function.
JuMP.normalized_coefficient
— Methodnormalized_coefficient(con_ref::ConstraintRef, variable::VariableRef)
Return the coefficient associated with variable
in constraint
after JuMP has normalized the constraint into its standard form. See also set_normalized_coefficient
.
JuMP.normalized_rhs
— Methodnormalized_rhs(con_ref::ConstraintRef)
Return the right-hand side term of con_ref
after JuMP has converted the constraint into its normalized form. See also set_normalized_rhs
.
JuMP.num_constraints
— Methodnum_constraints(model::Model, function_type, set_type)::Int64
Return the number of constraints currently in the model where the function has type function_type
and the set has type set_type
.
See also list_of_constraint_types
and all_constraints
.
Example
julia> model = Model();
julia> @variable(model, x >= 0, Bin);
julia> @variable(model, y);
julia> @constraint(model, y in MOI.GreaterThan(1.0));
julia> @constraint(model, y <= 1.0);
julia> @constraint(model, 2x <= 1);
julia> num_constraints(model, VariableRef, MOI.GreaterThan{Float64})
2
julia> num_constraints(model, VariableRef, MOI.ZeroOne)
1
julia> num_constraints(model, AffExpr, MOI.LessThan{Float64})
2
JuMP.num_nl_constraints
— Methodnum_nl_constraints(model::Model)
Returns the number of nonlinear constraints associated with the model
.
JuMP.num_variables
— Methodnum_variables(model::Model)::Int64
Returns number of variables in model
.
JuMP.object_dictionary
— Methodobject_dictionary(model::Model)
Return the dictionary that maps the symbol name of a variable, constraint, or expression to the corresponding object.
Objects are registered to a specific symbol in the macros. For example, @variable(model, x[1:2, 1:2])
registers the array of variables x
to the symbol :x
.
This method should be defined for any subtype of AbstractModel
.
JuMP.objective_bound
— Methodobjective_bound(model::Model)
Return the best known bound on the optimal objective value after a call to optimize!(model)
.
JuMP.objective_function
— Functionobjective_function(model::Model,
T::Type{<:AbstractJuMPScalar}=objective_function_type(model))
Return an object of type T
representing the objective function. Error if the objective is not convertible to type T
.
Examples
julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.
julia> @variable(model, x)
x
julia> @objective(model, Min, 2x + 1)
2 x + 1
julia> objective_function(model, AffExpr)
2 x + 1
julia> objective_function(model, QuadExpr)
2 x + 1
julia> typeof(objective_function(model, QuadExpr))
GenericQuadExpr{Float64,VariableRef}
We see with the last two commands that even if the objective function is affine, as it is convertible to a quadratic function, it can be queried as a quadratic function and the result is quadratic.
However, it is not convertible to a variable.
julia> objective_function(model, VariableRef)
ERROR: InexactError: convert(MathOptInterface.SingleVariable, MathOptInterface.ScalarAffineFunction{Float64}(MathOptInterface.ScalarAffineTerm{Float64}[MathOptInterface.ScalarAffineTerm{Float64}(2.0, MathOptInterface.VariableIndex(1))], 1.0))
[...]
JuMP.objective_function_string
— Methodobjective_function_string(print_mode, model::AbstractModel)::String
Return a String
describing the objective function of the model.
JuMP.objective_function_type
— Methodobjective_function_type(model::Model)::AbstractJuMPScalar
Return the type of the objective function.
JuMP.objective_sense
— Methodobjective_sense(model::Model)::MathOptInterface.OptimizationSense
Return the objective sense.
JuMP.objective_value
— Methodobjective_value(model::Model; result::Int = 1)
Return the objective value associated with result index result
of the most-recent solution returned by the solver.
See also: result_count
.
JuMP.operator_warn
— Methodoperator_warn(model::AbstractModel)
operator_warn(model::Model)
This function is called on the model whenever two affine expressions are added together without using destructive_add!
, and at least one of the two expressions has more than 50 terms.
For the case of Model
, if this function is called more than 20,000 times then a warning is generated once.
JuMP.optimize!
— Functionoptimize!(model::Model;
ignore_optimize_hook=(model.optimize_hook === nothing),
kwargs...)
Optimize the model. If an optimizer has not been set yet (see set_optimizer
), a NoOptimizer
error is thrown.
Keyword arguments kwargs
are passed to the optimize_hook
. An error is thrown if optimize_hook
is nothing
and keyword arguments are provided.
JuMP.optimizer_index
— Methodoptimizer_index(cr::ConstraintRef{Model})::MOI.ConstraintIndex
Return the index of the constraint that corresponds to cr
in the optimizer model. It throws NoOptimizer
if no optimizer is set and throws an ErrorException
if the optimizer is set but is not attached or if the constraint is bridged.
JuMP.optimizer_index
— Methodoptimizer_index(v::VariableRef)::MOI.VariableIndex
Return the index of the variable that corresponds to v
in the optimizer model. It throws NoOptimizer
if no optimizer is set and throws an ErrorException
if the optimizer is set but is not attached.
JuMP.optimizer_with_attributes
— Methodoptimizer_with_attributes(optimizer_constructor, attrs::Pair...)
Groups an optimizer constructor with the list of attributes attrs
. Note that it is equivalent to MOI.OptimizerWithAttributes
.
When provided to the Model
constructor or to set_optimizer
, it creates an optimizer by calling optimizer_constructor()
, and then sets the attributes using set_optimizer_attribute
.
Example
model = Model(
optimizer_with_attributes(
Gurobi.Optimizer, "Presolve" => 0, "OutputFlag" => 1
)
)
is equivalent to:
model = Model(Gurobi.Optimizer)
set_optimizer_attribute(model, "Presolve", 0)
set_optimizer_attribute(model, "OutputFlag", 1)
Note
The string names of the attributes are specific to each solver. One should consult the solver's documentation to find the attributes of interest.
See also: set_optimizer_attribute
, set_optimizer_attributes
, get_optimizer_attribute
.
JuMP.owner_model
— Functionowner_model(s::AbstractJuMPScalar)
Return the model owning the scalar s
.
JuMP.owner_model
— Methodowner_model(v::AbstractVariableRef)
Returns the model to which v
belongs.
Example
julia> model = Model();
julia> x = @variable(model)
noname
julia> owner_model(x) === model
true
JuMP.owner_model
— Methodowner_model(con_ref::ConstraintRef)
Returns the model to which con_ref
belongs.
JuMP.parse_one_operator_variable
— Functionparse_one_operator_variable(_error::Function, infoexpr::_VariableInfoExpr, sense::Val{S}, value) where S
Update infoexr
for a variable expression in the @variable
macro of the form variable name S value
.
JuMP.primal_status
— Methodprimal_status(model::Model; result::Int = 1)
Return the status of the most recent primal solution of the solver (i.e., the MathOptInterface model attribute PrimalStatus
) associated with the result index result
.
See also: result_count
.
JuMP.print_bridge_graph
— Method print_bridge_graph([io::IO,] model::Model)
Print the hyper-graph containing all variable, constraint, and objective types that could be obtained by bridging the variables, constraints, and objectives that are present in the model.
Each node in the hyper-graph corresponds to a variable, constraint, or objective type.
- Variable nodes are indicated by
[ ]
- Constraint nodes are indicated by
( )
- Objective nodes are indicated by
| |
The number inside each pair of brackets is an index of the node in the hyper-graph.
Note that this hyper-graph is the full list of possible transformations. When the bridged model is created, we select the shortest hyper-path(s) from this graph, so many nodes may be un-used.
For more information, see Legat, B., Dowson, O., Garcia, J., and Lubin, M. (2020). "MathOptInterface: a data structure for mathematical optimization problems." URL: https://arxiv.org/abs/2002.03447
JuMP.quad_terms
— Methodquad_terms(quad::GenericQuadExpr{C, V})
Provides an iterator over tuples (coefficient::C, var_1::V, var_2::V)
in the quadratic part of the quadratic expression.
JuMP.raw_status
— Methodraw_status(model::Model)
Return the reason why the solver stopped in its own words (i.e., the MathOptInterface model attribute RawStatusString
).
JuMP.read_from_file
— Methodread_from_file(
filename::String;
format::MOI.FileFormats.FileFormat = MOI.FileFormats.FORMAT_AUTOMATIC
)
Return a JuMP model read from filename
in the format format
.
If the filename ends in .gz
, it will be uncompressed using Gzip. If the filename ends in .bz2
, it will be uncompressed using BZip2.
JuMP.reduced_cost
— Methodreduced_cost(x::VariableRef)::Float64
Return the reduced cost associated with variable x
.
Equivalent to querying the shadow price of the active variable bound (if one exists and is active).
See also: shadow_price
.
JuMP.relative_gap
— Methodrelative_gap(model::Model)
Return the final relative optimality gap after a call to optimize!(model)
. Exact value depends upon implementation of MathOptInterface.RelativeGap() by the particular solver used for optimization.
JuMP.relax_integrality
— Methodrelax_integrality(model::Model)
Modifies model
to "relax" all binary and integrality constraints on variables. Specifically,
- Binary constraints are deleted, and variable bounds are tightened if necessary to ensure the variable is constrained to the interval $[0, 1]$.
- Integrality constraints are deleted without modifying variable bounds.
- An error is thrown if semi-continuous or semi-integer constraints are present (support may be added for these in the future).
- All other constraints are ignored (left in place). This includes discrete constraints like SOS and indicator constraints.
Returns a function that can be called without any arguments to restore the original model. The behavior of this function is undefined if additional changes are made to the affected variables in the meantime.
Example
julia> model = Model();
julia> @variable(model, x, Bin);
julia> @variable(model, 1 <= y <= 10, Int);
julia> @objective(model, Min, x + y);
julia> undo_relax = relax_integrality(model);
julia> print(model)
Min x + y
Subject to
x ≥ 0.0
y ≥ 1.0
x ≤ 1.0
y ≤ 10.0
julia> undo_relax()
julia> print(model)
Min x + y
Subject to
y ≥ 1.0
y ≤ 10.0
y integer
x binary
JuMP.reshape_set
— Functionreshape_set(vectorized_set::MOI.AbstractSet, shape::AbstractShape)
Return a set in its original shape shape
given its vectorized form vectorized_form
.
Examples
Given a SymmetricMatrixShape
of vectorized form [1, 2, 3] in MOI.PositiveSemidefinieConeTriangle(2)
, the following code returns the set of the original constraint Symmetric(Matrix[1 2; 2 3]) in PSDCone()
:
julia> reshape_set(MOI.PositiveSemidefiniteConeTriangle(2), SymmetricMatrixShape(2))
PSDCone()
JuMP.reshape_vector
— Functionreshape_vector(vectorized_form::Vector, shape::AbstractShape)
Return an object in its original shape shape
given its vectorized form vectorized_form
.
Examples
Given a SymmetricMatrixShape
of vectorized form [1, 2, 3]
, the following code returns the matrix Symmetric(Matrix[1 2; 2 3])
:
julia> reshape_vector([1, 2, 3], SymmetricMatrixShape(2))
2×2 LinearAlgebra.Symmetric{Int64,Array{Int64,2}}:
1 2
2 3
JuMP.result_count
— Methodresult_count(model::Model)
Return the number of results available to query after a call to optimize!
.
JuMP.sense_to_set
— Functionsense_to_set(_error::Function, ::Val{sense_symbol})
Converts a sense symbol to a set set
such that @constraint(model, func sense_symbol 0)
is equivalent to @constraint(model, func in set)
for any func::AbstractJuMPScalar
.
Example
Once a custom set is defined you can directly create a JuMP constraint with it:
julia> struct CustomSet{T} <: MOI.AbstractScalarSet
value::T
end
julia> Base.copy(x::CustomSet) = CustomSet(x.value)
julia> model = Model();
julia> @variable(model, x)
x
julia> cref = @constraint(model, x in CustomSet(1.0))
x ∈ CustomSet{Float64}(1.0)
However, there might be an appropriate sign that could be used in order to provide a more convenient syntax:
julia> JuMP.sense_to_set(::Function, ::Val{:⊰}) = CustomSet(0.0)
julia> MOIU.shift_constant(set::CustomSet, value) = CustomSet(set.value + value)
julia> cref = @constraint(model, x ⊰ 1)
x ∈ CustomSet{Float64}(1.0)
Note that the whole function is first moved to the right-hand side, then the sign is transformed into a set with zero constant and finally the constant is moved to the set with MOIU.shift_constant
.
JuMP.set_binary
— Methodset_binary(v::VariableRef)
Add a constraint on the variable v
that it must take values in the set $\{0,1\}$. See also unset_binary
.
JuMP.set_dual_start_value
— Methodset_dual_start_value(con_ref::ConstraintRef, value)
Set the dual start value (MOI attribute ConstraintDualStart
) of the constraint con_ref
to value
. To remove a dual start value set it to nothing
.
See also dual_start_value
.
JuMP.set_integer
— Methodset_integer(variable_ref::VariableRef)
Add an integrality constraint on the variable variable_ref
. See also unset_integer
.
JuMP.set_lower_bound
— Methodset_lower_bound(v::VariableRef, lower::Number)
Set the lower bound of a variable. If one does not exist, create a new lower bound constraint. See also delete_lower_bound
.
JuMP.set_name
— Methodset_name(con_ref::ConstraintRef, s::AbstractString)
Set a constraint's name attribute.
JuMP.set_name
— Methodset_name(v::VariableRef, s::AbstractString)
Set a variable's name attribute.
JuMP.set_normalized_coefficient
— Methodset_normalized_coefficient(con_ref::ConstraintRef, variable::VariableRef, value)
Set the coefficient of variable
in the constraint constraint
to value
.
Note that prior to this step, JuMP will aggregate multiple terms containing the same variable. For example, given a constraint 2x + 3x <= 2
, set_normalized_coefficient(con, x, 4)
will create the constraint 4x <= 2
.
model = Model()
@variable(model, x)
@constraint(model, con, 2x + 3x <= 2)
set_normalized_coefficient(con, x, 4)
con
# output
con : 4 x <= 2.0
JuMP.set_normalized_rhs
— Methodset_normalized_rhs(con_ref::ConstraintRef, value)
Set the right-hand side term of constraint
to value
.
Note that prior to this step, JuMP will aggregate all constant terms onto the right-hand side of the constraint. For example, given a constraint 2x + 1 <= 2
, set_normalized_rhs(con, 4)
will create the constraint 2x <= 4
, not 2x + 1 <= 4
.
julia> @constraint(model, con, 2x + 1 <= 2)
con : 2 x <= 1.0
julia> set_normalized_rhs(con, 4)
julia> con
con : 2 x <= 4.0
JuMP.set_objective
— Methodset_objective(model::AbstractModel, sense::MOI.OptimizationSense, func)
The functional equivalent of the @objective
macro.
Sets the objective sense and objective function simultaneously, and is equivalent to:
set_objective_sense(model, sense)
set_objective_function(model, func)
Examples
model = Model()
@variable(model, x)
set_objective(model, MOI.MIN_SENSE, x)
JuMP.set_objective_coefficient
— Methodset_objective_coefficient(model::Model, variable::VariableRef, coefficient::Real)
Set the linear objective coefficient associated with Variable
to coefficient
.
Note: this function will throw an error if a nonlinear objective is set.
JuMP.set_objective_function
— Functionset_objective_function(
model::Model,
func::Union{AbstractJuMPScalar, MathOptInterface.AbstractScalarFunction})
Sets the objective function of the model to the given function. See set_objective_sense
to set the objective sense. These are low-level functions; the recommended way to set the objective is with the @objective
macro.
JuMP.set_objective_sense
— Methodset_objective_sense(model::Model, sense::MathOptInterface.OptimizationSense)
Sets the objective sense of the model to the given sense. See set_objective_function
to set the objective function. These are low-level functions; the recommended way to set the objective is with the @objective
macro.
JuMP.set_optimizer
— Methodset_optimizer(model::Model, optimizer_factory;
bridge_constraints::Bool=true)
Creates an empty MathOptInterface.AbstractOptimizer
instance by calling optimizer_factory()
and sets it as the optimizer of model
. Specifically, optimizer_factory
must be callable with zero arguments and return an empty MathOptInterface.AbstractOptimizer
.
If bridge_constraints
is true, constraints that are not supported by the optimizer are automatically bridged to equivalent supported constraints when an appropriate transformation is defined in the MathOptInterface.Bridges
module or is defined in another module and is explicitly added.
See set_optimizer_attributes
and set_optimizer_attribute
for setting solver-specific parameters of the optimizer.
Examples
model = Model()
set_optimizer(model, GLPK.Optimizer)
JuMP.set_optimizer_attribute
— Methodset_optimizer_attribute(
model::Model, attr::MOI.AbstractOptimizerAttribute, value
)
Set the solver-specific attribute attr
in model
to value
.
Example
set_optimizer_attribute(model, MOI.Silent(), true)
See also: set_optimizer_attributes
, get_optimizer_attribute
.
JuMP.set_optimizer_attribute
— Methodset_optimizer_attribute(model::Model, name::String, value)
Sets solver-specific attribute identified by name
to value
.
Note that this is equivalent to set_optimizer_attribute(model, MOI.RawParameter(name), value)
.
Example
set_optimizer_attribute(model, "SolverSpecificAttributeName", true)
See also: set_optimizer_attributes
, get_optimizer_attribute
.
JuMP.set_optimizer_attributes
— Methodset_optimizer_attributes(model::Model, pairs::Pair...)
Given a list of attribute => value
pairs, calls set_optimizer_attribute(model, attribute, value)
for each pair.
Example
model = Model(Ipopt.Optimizer)
set_optimizer_attributes(model, "tol" => 1e-4, "max_iter" => 100)
is equivalent to:
model = Model(Ipopt.Optimizer)
set_optimizer_attribute(model, "tol", 1e-4)
set_optimizer_attribute(model, "max_iter", 100)
See also: set_optimizer_attribute
, get_optimizer_attribute
.
JuMP.set_silent
— Methodset_silent(model::Model)
Takes precedence over any other attribute controlling verbosity and requires the solver to produce no output.
JuMP.set_start_value
— Methodset_start_value(variable::VariableRef, value::Number)
Set the start value (MOI attribute VariablePrimalStart
) of the variable v
to value
. See also start_value
.
Note: VariablePrimalStart
s are sometimes called "MIP-starts" or "warmstarts".
JuMP.set_time_limit_sec
— Methodset_time_limit_sec(model::Model, limit)
Sets the time limit (in seconds) of the solver. Can be unset using unset_time_limit_sec
or with limit
set to nothing
.
JuMP.set_upper_bound
— Methodset_upper_bound(v::VariableRef,upper::Number)
Set the upper bound of a variable. If one does not exist, create an upper bound constraint. See also delete_upper_bound
.
JuMP.set_value
— Methodset_value(p::NonlinearParameter, v::Number)
Store the value v
in the nonlinear parameter p
.
Example
model = Model()
@NLparameter(model, p == 0)
set_value(p, 5)
value(p)
# output
5.0
JuMP.shadow_price
— Methodshadow_price(con_ref::ConstraintRef)
Return the change in the objective from an infinitesimal relaxation of the constraint.
This value is computed from dual
and can be queried only when has_duals
is true
and the objective sense is MIN_SENSE
or MAX_SENSE
(not FEASIBILITY_SENSE
). For linear constraints, the shadow prices differ at most in sign from the dual
value depending on the objective sense.
See also reduced_cost
.
Notes
- The function simply translates signs from
dual
and does not validate the conditions needed to guarantee the sensitivity interpretation of the shadow price. The caller is responsible, e.g., for checking whether the solver converged to an optimal primal-dual pair or a proof of infeasibility. - The computation is based on the current objective sense of the model. If this has changed since the last solve, the results will be incorrect.
- Relaxation of equality constraints (and hence the shadow price) is defined based on which sense of the equality constraint is active.
JuMP.shape
— Functionshape(c::AbstractConstraint)::AbstractShape
Return the shape of the constraint c
.
JuMP.show_constraints_summary
— Methodshow_constraints_summary(io::IO, model::AbstractModel)
Write to io
a summary of the number of constraints.
JuMP.show_objective_function_summary
— Methodshow_objective_function_summary(io::IO, model::AbstractModel)
Write to io
a summary of the objective function type.
JuMP.simplex_iterations
— Methodsimplex_iterations(model::Model)
Gets the cumulative number of simplex iterations during the most-recent optimization.
Solvers must implement MOI.SimplexIterations()
to use this function.
JuMP.solve_time
— Methodsolve_time(model::Model)
If available, returns the solve time reported by the solver. Returns "ArgumentError: ModelLike of type Solver.Optimizer
does not support accessing the attribute MathOptInterface.SolveTime()" if the attribute is not implemented.
JuMP.solver_name
— Methodsolver_name(model::Model)
If available, returns the SolverName
property of the underlying optimizer. Returns "No optimizer attached"
in AUTOMATIC
or MANUAL
modes when no optimizer is attached. Returns "SolverName() attribute not implemented by the optimizer." if the attribute is not implemented.
JuMP.start_value
— Methodstart_value(v::VariableRef)
Return the start value (MOI attribute VariablePrimalStart
) of the variable v
. See also set_start_value
.
Note: VariablePrimalStart
s are sometimes called "MIP-starts" or "warmstarts".
JuMP.termination_status
— Methodtermination_status(model::Model)
Return the reason why the solver stopped (i.e., the MathOptInterface model attribute TerminationStatus
).
JuMP.time_limit_sec
— Methodtime_limit_sec(model::Model)
Gets the time limit (in seconds) of the model (nothing
if unset). Can be set using set_time_limit_sec
.
JuMP.unfix
— Methodunfix(v::VariableRef)
Delete the fixing constraint of a variable.
JuMP.unregister
— Methodunregister(model::Model, key::Symbol)
Unregister the name key
from model
so that a new variable, constraint, or expression can be created with the same key.
Note that this will not delete the object model[key]
; it will just remove the reference at model[key]
. To delete the object, use
delete(model, model[key])
unregister(model, key)
Examples
```jldoctest; setup=:(model = Model()) julia> @variable(model, x) x
julia> @variable(model, x) ERROR: An object of name x is already attached to this model. If this is intended, consider using the anonymous construction syntax, e.g., x = @variable(model, [1:N], ...)
where the name of the object does not appear inside the macro.
Alternatively, use unregister(model, :x)
to first unregister the existing name from the model. Note that this will not delete the object; it will just remove the reference at model[:x]
. [...]
julia> num_variables(model) 1
julia> unregister(model, :x)
julia> @variable(model, x) x
julia> num_variables(model) 2
JuMP.unset_binary
— Methodunset_binary(variable_ref::VariableRef)
Remove the binary constraint on the variable variable_ref
.
JuMP.unset_integer
— Methodunset_integer(variable_ref::VariableRef)
Remove the integrality constraint on the variable variable_ref
.
JuMP.unset_silent
— Methodunset_silent(model::Model)
Neutralize the effect of the set_silent
function and let the solver attributes control the verbosity.
JuMP.unset_time_limit_sec
— Methodunset_time_limit_sec(model::Model)
Unsets the time limit of the solver. Can be set using set_time_limit_sec
.
JuMP.upper_bound
— Methodupper_bound(v::VariableRef)
Return the upper bound of a variable. Error if one does not exist. See also has_upper_bound
.
JuMP.value
— Methodvalue(con_ref::ConstraintRef; result::Int = 1)
Return the primal value of constraint con_ref
associated with result index result
of the most-recent solution returned by the solver.
That is, if con_ref
is the reference of a constraint func
-in-set
, it returns the value of func
evaluated at the value of the variables (given by value(::VariableRef)
).
Use has_values
to check if a result exists before asking for values.
See also: result_count
.
Note
For scalar contraints, the constant is moved to the set
so it is not taken into account in the primal value of the constraint. For instance, the constraint @constraint(model, 2x + 3y + 1 == 5)
is transformed into 2x + 3y
-in-MOI.EqualTo(4)
so the value returned by this function is the evaluation of 2x + 3y
. ```
JuMP.value
— Methodvalue(con_ref::ConstraintRef, var_value::Function)
Evaluate the primal value of the constraint con_ref
using var_value(v)
as the value for each variable v
.
JuMP.value
— Methodvalue(v::GenericAffExpr; result::Int = 1)
Return the value of the GenericAffExpr
v
associated with result index result
of the most-recent solution returned by the solver.
Replaces getvalue
for most use cases.
See also: result_count
.
JuMP.value
— Methodvalue(v::GenericQuadExpr; result::Int = 1)
Return the value of the GenericQuadExpr
v
associated with result index result
of the most-recent solution returned by the solver.
Replaces getvalue
for most use cases.
See also: result_count
.
JuMP.value
— Methodvalue(ex::NonlinearExpression, var_value::Function)
Evaluate ex
using var_value(v)
as the value for each variable v
.
JuMP.value
— Methodvalue(ex::NonlinearExpression; result::Int = 1)
Return the value of the NonlinearExpression
ex
associated with result index result
of the most-recent solution returned by the solver.
Replaces getvalue
for most use cases.
See also: result_count
.
JuMP.value
— Methodvalue(p::NonlinearParameter)
Return the current value stored in the nonlinear parameter p
.
Example
model = Model()
@NLparameter(model, p == 10)
value(p)
# output
10.0
JuMP.value
— Methodvalue(v::VariableRef, var_value::Function)
Evaluate the value of the variable v
as var_value(v)
.
JuMP.value
— Methodvalue(v::VariableRef; result = 1)
Return the value of variable v
associated with result index result
of the most-recent returned by the solver.
Use has_values
to check if a result exists before asking for values.
See also: result_count
.
JuMP.value
— Methodvalue(ex::GenericAffExpr, var_value::Function)
Evaluate ex
using var_value(v)
as the value for each variable v
.
JuMP.variable_by_name
— Methodvariable_by_name(model::AbstractModel,
name::String)::Union{AbstractVariableRef, Nothing}
Returns the reference of the variable with name attribute name
or Nothing
if no variable has this name attribute. Throws an error if several variables have name
as their name attribute.
julia> model = Model();
julia> @variable(model, x)
x
julia> variable_by_name(model, "x")
x
julia> @variable(model, base_name="x")
x
julia> variable_by_name(model, "x")
ERROR: Multiple variables have the name x.
Stacktrace:
[1] error(::String) at ./error.jl:33
[2] get(::MOIU.Model{Float64}, ::Type{MathOptInterface.VariableIndex}, ::String) at /home/blegat/.julia/dev/MathOptInterface/src/Utilities/model.jl:222
[3] get at /home/blegat/.julia/dev/MathOptInterface/src/Utilities/universalfallback.jl:201 [inlined]
[4] get(::MathOptInterface.Utilities.CachingOptimizer{MathOptInterface.AbstractOptimizer,MathOptInterface.Utilities.UniversalFallback{MOIU.Model{Float64}}}, ::Type{MathOptInterface.VariableIndex}, ::String) at /home/blegat/.julia/dev/MathOptInterface/src/Utilities/cachingoptimizer.jl:490
[5] variable_by_name(::Model, ::String) at /home/blegat/.julia/dev/JuMP/src/variables.jl:268
[6] top-level scope at none:0
julia> var = @variable(model, base_name="y")
y
julia> variable_by_name(model, "y")
y
julia> set_name(var, "z")
julia> variable_by_name(model, "y")
julia> variable_by_name(model, "z")
z
julia> @variable(model, u[1:2])
2-element Array{VariableRef,1}:
u[1]
u[2]
julia> variable_by_name(model, "u[2]")
u[2]
JuMP.variable_ref_type
— Methodvariable_ref_type(::GenericAffExpr{C, V}) where {C, V}
A helper function used internally by JuMP and some JuMP extensions. Returns the variable type V
from a GenericAffExpr
JuMP.write_to_file
— Methodwrite_to_file(
model::Model,
filename::String;
format::MOI.FileFormats.FileFormat = MOI.FileFormats.FORMAT_AUTOMATIC
)
Write the JuMP model model
to filename
in the format format
.
If the filename ends in .gz
, it will be compressed using Gzip. If the filename ends in .bz2
, it will be compressed using BZip2.
MathOptInterface.get
— Methodget(model::Model, attr::MathOptInterface.AbstractModelAttribute)
Return the value of the attribute attr
from the model's MOI backend.
MathOptInterface.get
— Methodget(model::Model, attr::MathOptInterface.AbstractOptimizerAttribute)
Return the value of the attribute attr
from the model's MOI backend.
JuMP.@NLconstraint
— Macro@NLconstraint(m::Model, expr)
Add a constraint described by the nonlinear expression expr
. See also @constraint
. For example:
@NLconstraint(model, sin(x) <= 1)
@NLconstraint(model, [i = 1:3], sin(i * x) <= 1 / i)
JuMP.@NLconstraints
— Macro@NLconstraints(model, args...)
Adds multiple nonlinear constraints to model at once, in the same fashion as the @NLconstraint
macro.
The model must be the first argument, and multiple variables can be added on multiple lines wrapped in a begin ... end
block.
Examples
@NLconstraints(model, begin
t >= sqrt(x^2 + y^2)
[i = 1:2], z[i] <= log(a[i])
end)
JuMP.@NLexpression
— Macro@NLexpression(args...)
Efficiently build a nonlinear expression which can then be inserted in other nonlinear constraints and the objective. See also [@expression
]. For example:
@NLexpression(model, my_expr, sin(x)^2 + cos(x^2))
@NLconstraint(model, my_expr + y >= 5)
@NLobjective(model, Min, my_expr)
Indexing over sets and anonymous expressions are also supported:
@NLexpression(m, my_expr_1[i=1:3], sin(i * x))
my_expr_2 = @NLexpression(m, log(1 + sum(exp(x[i])) for i in 1:2))
JuMP.@NLexpressions
— Macro@NLexpressions(model, args...)
Adds multiple nonlinear expressions to model at once, in the same fashion as the @NLexpression
macro.
The model must be the first argument, and multiple variables can be added on multiple lines wrapped in a begin ... end
block.
Examples
@NLexpressions(model, begin
my_expr, sqrt(x^2 + y^2)
my_expr_1[i = 1:2], log(a[i]) - z[i]
end)
JuMP.@NLobjective
— Macro@NLobjective(model, sense, expression)
Add a nonlinear objective to model
with optimization sense sense
. sense
must be Max
or Min
.
Example
@NLobjective(model, Max, 2x + 1 + sin(x))
JuMP.@NLparameter
— Macro@NLparameter(model, param == value)
Create and return a nonlinear parameter param
attached to the model model
with initial value set to value
. Nonlinear parameters may be used only in nonlinear expressions.
Example
model = Model()
@NLparameter(model, x == 10)
value(x)
# output
10.0
@NLparameter(model, param_collection[...] == value_expr)
Create and return a collection of nonlinear parameters param_collection
attached to the model model
with initial value set to value_expr
(may depend on index sets). Uses the same syntax for specifying index sets as @variable
.
Example
model = Model()
@NLparameter(model, y[i = 1:10] == 2 * i)
value(y[9])
# output
18.0
JuMP.@SDconstraint
— Macro@SDconstraint(model::Model, expr)
Add a semidefinite constraint described by the expression expr
.
@SDconstraint(model::Model, ref[i=..., j=..., ...], expr)
Add a group of semidefinite constraints described by the expression expr
parametrized by i
, j
, ...
The expression expr
needs to be of the form a sign b
where sign
is ⪰
, ≥
, >=
, ⪯
, ≤
or <=
and a
and b
are square
matrices. It constrains the square matrix x
(or -x
if the sign is ⪯
, ≤
or <=
) to be symmetric and positive semidefinite where
x = a
, ifb
is the symbol0
,x = -b
, ifa
is the symbol0
,- otherwise,
x = a - b
.
By default, we check numerical symmetry of the matrix x
, and if symmetry is violated by some arbitrary amount, we add explicit equality constraints. You can use Symmetric(x) in PSDCone()
with the @constraint
macro to skip these checks if you know the matrix must be symmetric; see PSDCone
for more information.
Examples
The following constrains the matrix [x-1 2x-2; -3 x-4]
to be symmetric and positive semidefinite, that is, it constrains 2x-2
to be equal to -3
and constrains all eigenvalues of the matrix to be nonnegative.
julia> model = Model();
julia> @variable(model, x)
x
julia> a = [x 2x
0 x];
julia> b = [1 2
3 4];
julia> cref = @SDconstraint(model, a ⪰ b)
[x - 1 2 x - 2;
-3 x - 4 ] ∈ PSDCone()
julia> jump_function(constraint_object(cref))
4-element Array{GenericAffExpr{Float64,VariableRef},1}:
x - 1
-3
2 x - 2
x - 4
julia> moi_set(constraint_object(cref))
MathOptInterface.PositiveSemidefiniteConeSquare(2)
In the set PositiveSemidefiniteConeSquare(2)
in the last output, Square
means that the matrix is passed as a square matrix as the corresponding off-diagonal entries need to be constrained to be equal. A similar set PositiveSemidefiniteConeTriangle
exists which only uses the upper triangular part of the matrix assuming that it is symmetric, see PSDCone
to see how to use it.
JuMP.@SDconstraints
— Macro@SDconstraints(model, args...)
Adds multiple semi-definite constraints to model at once, in the same fashion as the @SDconstraint
macro.
The model must be the first argument, and multiple constraints can be added on multiple lines wrapped in a begin ... end
block.
Examples
@SDconstraints(model, begin
A * x >= b
b - C * y >= 0
end)
JuMP.@build_constraint
— Macro@build_constraint(constraint_expr)
Constructs a ScalarConstraint
or VectorConstraint
using the same machinery as @constraint
but without adding the constraint to a model.
Constraints using broadcast operators like x .<= 1
are also supported and will create arrays of ScalarConstraint
or VectorConstraint
.
Examples
model = Model();
@variable(model, x);
@build_constraint(2x >= 1)
# output
ScalarConstraint{GenericAffExpr{Float64,VariableRef},MathOptInterface.GreaterThan{Float64}}(2 x, MathOptInterface.GreaterThan{Float64}(1.0))
JuMP.@constraint
— Macro@constraint(m::Model, expr)
Add a constraint described by the expression expr
.
@constraint(m::Model, ref[i=..., j=..., ...], expr)
Add a group of constraints described by the expression expr
parametrized by i
, j
, ...
The expression expr
can either be
- of the form
func in set
constraining the functionfunc
to belong to the setset
which is either aMOI.AbstractSet
or one of the JuMP shortcutsSecondOrderCone
,RotatedSecondOrderCone
andPSDCone
, e.g.@constraint(model, [1, x-1, y-2] in SecondOrderCone())
constrains the norm of[x-1, y-2]
be less than 1; - of the form
a sign b
, wheresign
is one of==
,≥
,>=
,≤
and<=
building the single constraint enforcing the comparison to hold for the expressiona
andb
, e.g.@constraint(m, x^2 + y^2 == 1)
constrainsx
andy
to lie on the unit circle; - of the form
a ≤ b ≤ c
ora ≥ b ≥ c
(where≤
and<=
(resp.≥
and>=
) can be used interchangeably) constraining the paired the expressionb
to lie betweena
andc
; - of the forms
@constraint(m, a .sign b)
or@constraint(m, a .sign b .sign c)
which broadcast the constraint creation to each element of the vectors.
Note for extending the constraint macro
Each constraint will be created using add_constraint(m, build_constraint(_error, func, set))
where
_error
is an error function showing the constraint call in addition to the error message given as argument,func
is the expression that is constrained- and
set
is the set in which it is constrained to belong.
For expr
of the first type (i.e. @constraint(m, func in set)
), func
and set
are passed unchanged to build_constraint
but for the other types, they are determined from the expressions and signs. For instance, @constraint(m, x^2 + y^2 == 1)
is transformed into add_constraint(m, build_constraint(_error, x^2 + y^2, MOI.EqualTo(1.0)))
.
To extend JuMP to accept new constraints of this form, it is necessary to add the corresponding methods to build_constraint
. Note that this will likely mean that either func
or set
will be some custom type, rather than e.g. a Symbol
, since we will likely want to dispatch on the type of the function or set appearing in the constraint.
JuMP.@constraints
— Macro@constraints(model, args...)
Adds groups of constraints at once, in the same fashion as the @constraint
macro.
The model must be the first argument, and multiple constraints can be added on multiple lines wrapped in a begin ... end
block.
Examples
@constraints(model, begin
x >= 1
y - w <= 2
sum_to_one[i=1:3], z[i] + y == 1
end)
JuMP.@expression
— Macro@expression(args...)
Efficiently builds a linear or quadratic expression but does not add to model immediately. Instead, returns the expression which can then be inserted in other constraints. For example:
@expression(m, shared, sum(i*x[i] for i=1:5))
@constraint(m, shared + y >= 5)
@constraint(m, shared + z <= 10)
The ref
accepts index sets in the same way as @variable
, and those indices can be used in the construction of the expressions:
@expression(m, expr[i=1:3], i*sum(x[j] for j=1:3))
Anonymous syntax is also supported:
expr = @expression(m, [i=1:3], i*sum(x[j] for j=1:3))
JuMP.@expressions
— Macro@expressions(model, args...)
Adds multiple expressions to model at once, in the same fashion as the @expression
macro.
The model must be the first argument, and multiple variables can be added on multiple lines wrapped in a begin ... end
block.
Examples
@expressions(model, begin
my_expr, x^2 + y^2
my_expr_1[i = 1:2], a[i] - z[i]
end)
JuMP.@objective
— Macro@objective(model::Model, sense, func)
Set the objective sense to sense
and objective function to func
. The objective sense can be either Min
, Max
, MathOptInterface.MIN_SENSE
, MathOptInterface.MAX_SENSE
or MathOptInterface.FEASIBILITY_SENSE
; see MathOptInterface.ObjectiveSense
. In order to set the sense programatically, i.e., when sense
is a Julia variable whose value is the sense, one of the three MathOptInterface.ObjectiveSense
values should be used. The function func
can be a single JuMP variable, an affine expression of JuMP variables or a quadratic expression of JuMP variables.
Examples
To minimize the value of the variable x
, do as follows:
julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.
julia> @variable(model, x)
x
julia> @objective(model, Min, x)
x
To maximize the value of the affine expression 2x - 1
, do as follows:
julia> @objective(model, Max, 2x - 1)
2 x - 1
To set a quadratic objective and set the objective sense programatically, do as follows:
julia> sense = MOI.MIN_SENSE
MIN_SENSE::OptimizationSense = 0
julia> @objective(model, sense, x^2 - 2x + 1)
x² - 2 x + 1
JuMP.@variable
— Macro@variable(model, kw_args...)
Add an anonymous variable to the model model
described by the keyword arguments kw_args
and returns the variable.
@variable(model, expr, args..., kw_args...)
Add a variable to the model model
described by the expression expr
, the positional arguments args
and the keyword arguments kw_args
. The expression expr
can either be (note that in the following the symbol <=
can be used instead of ≤
and the symbol >=
can be used instead of ≥
)
- of the form
varexpr
creating variables described byvarexpr
; - of the form
varexpr ≤ ub
(resp.varexpr ≥ lb
) creating variables described byvarexpr
with upper bounds given byub
(resp. lower bounds given bylb
); - of the form
varexpr == value
creating variables described byvarexpr
with fixed values given byvalue
; or - of the form
lb ≤ varexpr ≤ ub
orub ≥ varexpr ≥ lb
creating variables described byvarexpr
with lower bounds given bylb
and upper bounds given byub
. - of the form
varexpr in set
creating variables described byvarexpr
constrained to belong toset
, see Variables constrained on creation.
The expression varexpr
can either be
- of the form
varname
creating a scalar real variable of namevarname
; - of the form
varname[...]
or[...]
creating a container of variables (see Containers in macros).
The recognized positional arguments in args
are the following:
Bin
: Sets the variable to be binary, i.e. either 0 or 1.Int
: Sets the variable to be integer, i.e. one of ..., -2, -1, 0, 1, 2, ...Symmetric
: Only available when creating a square matrix of variables, i.e. whenvarexpr
is of the formvarname[1:n,1:n]
orvarname[i=1:n,j=1:n]
. It creates a symmetric matrix of variable, that is, it only creates a new variable forvarname[i,j]
withi ≤ j
and setsvarname[j,i]
to the same variable asvarname[i,j]
. It is equivalent to usingvarexpr in SymMatrixSpace()
asexpr
.PSD
: The square matrix of variable is bothSymmetric
and constrained to be positive semidefinite. It is equivalent to usingvarexpr in PSDCone()
asexpr
.
The recognized keyword arguments in kw_args
are the following:
base_name
: Sets the name prefix used to generate variable names. It corresponds to the variable name for scalar variable, otherwise, the variable names are set tobase_name[...]
for each index...
of the axesaxes
.lower_bound
: Sets the value of the variable lower bound.upper_bound
: Sets the value of the variable upper bound.start
: Sets the variable starting value used as initial guess in optimization.binary
: Sets whether the variable is binary or not.integer
: Sets whether the variable is integer or not.variable_type
: See the "Note for extending the variable macro" section below.set
: Equivalent to usingvarexpr in value
asexpr
wherevalue
is the value of the keyword argument.container
: Specify the container type, see Containers in macros.
Examples
The following are equivalent ways of creating a variable x
of name x
with lower bound 0:
# Specify everything in `expr`
@variable(model, x >= 0)
# Specify the lower bound using a keyword argument
@variable(model, x, lower_bound=0)
# Specify everything in `kw_args`
x = @variable(model, base_name="x", lower_bound=0)
The following are equivalent ways of creating a DenseAxisArray
of index set [:a, :b]
and with respective upper bounds 2 and 3 and names x[a]
and x[b]
. The upper bound can either be specified in expr
:
ub = Dict(:a => 2, :b => 3)
@variable(model, x[i=keys(ub)] <= ub[i])
# output
1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:
Dimension 1, Symbol[:a, :b]
And data, a 2-element Array{VariableRef,1}:
x[a]
x[b]
or it can be specified with the upper_bound
keyword argument:
@variable(model, y[i=keys(ub)], upper_bound=ub[i])
# output
1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:
Dimension 1, Symbol[:a, :b]
And data, a 2-element Array{VariableRef,1}:
y[a]
y[b]
Note for extending the variable macro
The single scalar variable or each scalar variable of the container are created using add_variable(model, build_variable(_error, info, extra_args...; extra_kw_args...))
where
model
is the model passed to the@variable
macro;_error
is an error function with a singleString
argument showing the@variable
call in addition to the error message given as argument;info
is theVariableInfo
struct containing the information gathered inexpr
, the recognized keyword arguments (exceptbase_name
andvariable_type
) and the recognized positional arguments (exceptSymmetric
andPSD
);extra_args
are the unrecognized positional arguments ofargs
plus the value of thevariable_type
keyword argument if present. Thevariable_type
keyword argument allows the user to pass a position argument tobuild_variable
without the need to give a positional argument to@variable
. In particular, this allows the user to give a positional argument to thebuild_variable
call when using the anonymous single variable syntax@variable(model, kw_args...)
; andextra_kw_args
are the unrecognized keyword argument ofkw_args
.
Examples
The following creates a variable x
of name x
with lower_bound
0 as with the first example above but does it without using the @variable
macro
info = VariableInfo(true, 0, false, NaN, false, NaN, false, NaN, false, false)
JuMP.add_variable(model, JuMP.build_variable(error, info), "x")
The following creates a DenseAxisArray
of index set [:a, :b]
and with respective upper bounds 2 and 3 and names x[a]
and x[b]
as with the second example above but does it without using the @variable
macro
# Without the `@variable` macro
x = JuMP.Containers.container(i -> begin
info = VariableInfo(false, NaN, true, ub[i], false, NaN, false, NaN, false, false)
x[i] = JuMP.add_variable(model, JuMP.build_variable(error, info), "x[$i]")
end, JuMP.Containers.vectorized_product(keys(ub)))
# output
1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:
Dimension 1, Symbol[:a, :b]
And data, a 2-element Array{VariableRef,1}:
x[a]
x[b]
The following are equivalent ways of creating a Matrix
of size N x N
with variables custom variables created with a JuMP extension using the Poly(X)
positional argument to specify its variables:
# Using the `@variable` macro
@variable(model, x[1:N,1:N], Symmetric, Poly(X))
# Without the `@variable` macro
x = Matrix{JuMP.variable_type(model, Poly(X))}(N, N)
info = VariableInfo(false, NaN, false, NaN, false, NaN, false, NaN, false, false)
for i in 1:N, j in i:N
x[i,j] = x[j,i] = JuMP.add_variable(model, build_variable(error, info, Poly(X)), "x[$i,$j]")
end
JuMP.@variables
— Macro@variables(model, args...)
Adds multiple variables to model at once, in the same fashion as the @variable
macro.
The model must be the first argument, and multiple variables can be added on multiple lines wrapped in a begin ... end
block.
Examples
@variables(model, begin
x
y[i = 1:2] >= 0, (start = i)
z, Bin, (start = 0, base_name = "Z")
end)
Keyword arguments must be contained within parentheses (refer to the example above).