LP and MILP API Reference#
- class cuopt.linear_programming.problem.VType(*values)#
The type of a variable is either continuous or integer. Variable Types can be directly used as a constant. CONTINUOUS is VType.CONTINUOUS INTEGER is VType.INTEGER
- CONTINUOUS = 'C'#
- INTEGER = 'I'#
- class cuopt.linear_programming.problem.CType(*values)#
The sense of a constraint is either LE, GE or EQ. Constraint Sense Types can be directly used as a constant. LE is CType.LE GE is CType.GE EQ is CType EQ
- LE = 'L'#
- GE = 'G'#
- EQ = 'E'#
- class cuopt.linear_programming.problem.sense(*values)#
The sense of a model is either MINIMIZE or MAXIMIZE. Model objective sense can be directly used as a constant. MINIMIZE is sense.MINIMIZE MAXIMIZE is sense.MAXIMIZE
- class cuopt.linear_programming.solver_settings.SolverSettings#
Methods
Return callback class object
get_parameter
(name)Get the value of a parameter used by cuOpt's LP/MIP solvers.
Returns the warm start data.
set_mip_callback
(callback)Note: Only supported for MILP
set_optimality_tolerance
(eps_optimal)NOTE: Not supported for MILP, absolute is fixed to 1e-4,
set_parameter
(name, value)Set the value of a parameter used by cuOpt's LP/MIP solvers.
set_pdlp_warm_start_data
(pdlp_warm_start_data)Set the pdlp warm start data.
to_base_type
(value)Convert a string to a base type.
toDict
- to_base_type(value)#
Convert a string to a base type.
- Parameters:
- valuestr
The value to convert.
- Returns:
- valuefloat, int, bool, or str
The converted value.
- get_parameter(name)#
Get the value of a parameter used by cuOpt’s LP/MIP solvers.
- Parameters:
- namestr
The name of the parameter to get.
- Returns:
- valuefloat, int, bool, or str
The value of the parameter.
Notes
For a list of availabe parameters, their descriptions, default values, and acceptable ranges, see the cuOpt documentation parameter.rst.
- set_parameter(name, value)#
Set the value of a parameter used by cuOpt’s LP/MIP solvers.
- Parameters:
- namestr
The name of the parameter to set.
- valuestr
The value the parameter should take.
- For a list of availabe parameters, their descriptions, default values,
- and acceptable ranges, see the cuOpt documentation `parameter.rst`.
- set_optimality_tolerance(eps_optimal)#
NOTE: Not supported for MILP, absolute is fixed to 1e-4,
Set both absolute and relative tolerance on the primal feasibility, dual feasibility, and gap. Changing this value has a significant impact on accuracy and runtime.
Optimality is computed as follows:
- dual_feasibility < absolute_dual_tolerance + relative_dual_tolerance
norm_objective_coefficient (l2_norm(c))
- primal_feasibility < absolute_primal_tolerance
relative_primal_tolerance * norm_constraint_bounds (l2_norm(b))
- duality_gap < absolute_gap_tolerance + relative_gap_tolerance
(abs(primal_objective) + abs(dual_objective))
If all three conditions hold, optimality is reached.
- Parameters:
- eps_optimalfloat64
Tolerance to optimality
- Notes
- —–
- Default value is 1e-4.
- To set each absolute and relative tolerance, use the provided setters.
- set_pdlp_warm_start_data(pdlp_warm_start_data)#
Set the pdlp warm start data. This allows to restart PDLP with a previous solution context.
This should be used when you solve a new problem which is similar to the previous one.
- Parameters:
- pdlp_warm_start_dataPDLPWarmStartData
PDLP warm start data.
Notes
For now, the problem must have the same number of variables and constraints as the one found in the previous solution.
Only supported solver modes are Stable2 and Fast1.
Examples
>>> solution = solver.Solve(first_problem, settings) >>> settings.set_pdlp_warm_start_data( >>> solution.get_pdlp_warm_start_data() >>> ) >>> solution = solver.Solve(second_problem, settings)
- set_mip_callback(callback)#
Note: Only supported for MILP
Set the callback to receive incumbent solution.
- Parameters:
- callbackclass for function callback
Callback class that inherits from GetSolutionCallback or SetSolutionCallback.
Examples
>>> # Callback for incumbent solution >>> class CustomGetSolutionCallback(GetSolutionCallback): >>> def __init__(self): >>> super().__init__() >>> self.n_callbacks = 0 >>> self.solutions = [] >>> >>> def get_solution(self, solution, solution_cost): >>> self.n_callbacks += 1 >>> assert len(solution) > 0 >>> assert len(solution_cost) == 1 >>> >>> self.solutions.append( >>> { >>> "solution": solution.copy_to_host(), >>> "cost": solution_cost.copy_to_host()[0], >>> } >>> ) >>> >>> class CustomSetSolutionCallback(SetSolutionCallback): >>> def __init__(self, get_callback): >>> super().__init__() >>> self.n_callbacks = 0 >>> self.get_callback = get_callback >>> >>> def set_solution(self, solution, solution_cost): >>> self.n_callbacks += 1 >>> if self.get_callback.solutions: >>> solution[:] = >>> self.get_callback.solutions[-1]["solution"] >>> solution_cost[0] = float( >>> self.get_callback.solutions[-1]["cost"] >>> ) >>> >>> get_callback = CustomGetSolutionCallback() >>> set_callback = CustomSetSolutionCallback(get_callback) >>> settings.set_mip_callback(get_callback) >>> settings.set_mip_callback(set_callback)
- get_mip_callbacks()#
Return callback class object
- get_pdlp_warm_start_data()#
Returns the warm start data. See set_pdlp_warm_start_data for more details.
- Returns:
- pdlp_warm_start_data
Notes
…
- toDict()#
- class cuopt.linear_programming.solution.solution.PDLPWarmStartData(
- current_primal_solution,
- current_dual_solution,
- initial_primal_average,
- initial_dual_average,
- current_ATY,
- sum_primal_solutions,
- sum_dual_solutions,
- last_restart_duality_gap_primal_solution,
- last_restart_duality_gap_dual_solution,
- initial_primal_weight,
- initial_step_size,
- total_pdlp_iterations,
- total_pdhg_iterations,
- last_candidate_kkt_score,
- last_restart_kkt_score,
- sum_solution_weight,
- iterations_since_last_restart,
- class cuopt.linear_programming.problem.Problem(model_name='')#
Bases:
object
A Problem defines a Linear Program or Mixed Integer Program Variable can be be created by calling addVariable() Constraints can be added by calling addConstraint() The objective can be set by calling setObjective() The problem data is formed when calling solve().
- Parameters:
- model_namestr, optional
Name of the model. Default is an empty string.
Examples
>>> problem = problem.Problem("MIP_model") >>> x = problem.addVariable(lb=-2.0, ub=8.0, vtype=INTEGER) >>> y = problem.addVariable(name="Var2") >>> problem.addConstraint(2*x - 3*y <= 10, name="Constr1") >>> expr = 3*x + y >>> problem.addConstraint(expr + x == 20, name="Constr2") >>> problem.setObjective(x + y, sense=MAXIMIZE) >>> problem.solve()
Attributes
Name
(str) Name of the model.
ObjSense
(sense) Objective sense (MINIMIZE or MAXIMIZE).
ObjConstant
(float) Constant term in the objective.
Status
(int) Status of the problem after solving.
SolveTime
(float) Time taken to solve the problem.
SolutionStats
(object) Solution statistics for LP or MIP problem.
ObjValue
(float) Objective value of the problem.
IsMIP
(bool) Indicates if the problem is a Mixed Integer Program.
NumVariables
(int) Number of Variables in the problem.
NumConstraints
(int) Number of constraints in the problem.
NumNZs
(int) Number of non-zeros in the problem.
Methods
addConstraint
(constr[, name])Adds a constraint to the problem defined by constraint object and name.
addVariable
([lb, ub, obj, vtype, name])Adds a variable to the problem defined by lower bound, upper bound, type and name.
getCSR
()Computes and returns the CSR representation of the constraint matrix.
Get a list of all the Constraints in a problem.
Get the Objective expression of the problem.
Get a list of all the variables in the problem.
get_incumbent_values
(solution, vars)Extract incumbent values of the vars from a problem solution.
setObjective
(expr[, sense])Set the Objective of the problem with an expression that needs to be MINIMIZED or MAXIMIZED.
solve
([settings])Optimizes the LP or MIP problem with the added variables, constraints and objective.
- addConstraint(constr, name='')#
Adds a constraint to the problem defined by constraint object and name. A constraint is generated using LinearExpression, Sense and RHS.
- Parameters:
- constrConstraint
Constructed using LinearExpressions (See Examples)
- namestring
Name of the variable. Optional.
Examples
>>> problem = problem.Problem("MIP_model") >>> x = problem.addVariable(lb=-2.0, ub=8.0, vtype=INTEGER) >>> y = problem.addVariable(name="Var2") >>> problem.addConstraint(2*x - 3*y <= 10, name="Constr1") >>> expr = 3*x + y >>> problem.addConstraint(expr + x == 20, name="Constr2")
- addVariable(
- lb=0.0,
- ub=inf,
- obj=0.0,
- vtype=VType.CONTINUOUS,
- name='',
Adds a variable to the problem defined by lower bound, upper bound, type and name.
- Parameters:
- lbfloat
Lower bound of the variable. Defaults to 0.
- ubfloat
Upper bound of the variable. Defaults to infinity.
- vtypeenum
vtype.CONTINUOUS or vtype.INTEGER. Defaults to CONTINUOUS.
- namestring
Name of the variable. Optional.
Examples
>>> problem = problem.Problem("MIP_model") >>> x = problem.addVariable(lb=-2.0, ub=8.0, vtype=INTEGER, name="Var1")
- getCSR()#
Computes and returns the CSR representation of the constraint matrix.
- getConstraints()#
Get a list of all the Constraints in a problem.
- getObjective()#
Get the Objective expression of the problem.
- getVariables()#
Get a list of all the variables in the problem.
- get_incumbent_values(solution, vars)#
Extract incumbent values of the vars from a problem solution.
- setObjective(expr, sense=sense.MINIMIZE)#
Set the Objective of the problem with an expression that needs to be MINIMIZED or MAXIMIZED.
- Parameters:
- exprLinearExpression or Variable or Constant
Objective expression that needs maximization or minimization.
- senseenum
Sets whether the problem is a maximization or a minimization problem. Values passed can either be MINIMIZE or MAXIMIZE. Defaults to MINIMIZE.
Examples
>>> problem = problem.Problem("MIP_model") >>> x = problem.addVariable(lb=-2.0, ub=8.0, vtype=INTEGER) >>> y = problem.addVariable(name="Var2") >>> problem.addConstraint(2*x - 3*y <= 10, name="Constr1") >>> expr = 3*x + y >>> problem.addConstraint(expr + x == 20, name="Constr2") >>> problem.setObjective(x + y, sense=MAXIMIZE)
- solve(
- settings=<cuopt.linear_programming.solver_settings.solver_settings.SolverSettings object>,
Optimizes the LP or MIP problem with the added variables, constraints and objective.
Examples
>>> problem = problem.Problem("MIP_model") >>> x = problem.addVariable(lb=-2.0, ub=8.0, vtype=INTEGER) >>> y = problem.addVariable(name="Var2") >>> problem.addConstraint(2*x - 3*y <= 10, name="Constr1") >>> expr = 3*x + y >>> problem.addConstraint(expr + x == 20, name="Constr2") >>> problem.setObjective(x + y, sense=MAXIMIZE) >>> problem.solve()
- class cuopt.linear_programming.problem.Variable(lb=0.0, ub=inf, obj=0.0, vtype=VType.CONTINUOUS, vname='')#
Bases:
object
cuOpt variable object initialized with details of the variable such as lower bound, upper bound, type and name. Variables are always associated with a problem and can be created using problem.addVariable (See problem class).
- Parameters:
- lbfloat
Lower bound of the variable. Defaults to 0.
- ubfloat
Upper bound of the variable. Defaults to infinity.
- vtypeenum
CONTINUOUS or INTEGER. Defaults to CONTINUOUS.
- objfloat
Coefficient of the Variable in the objective.
- namestr
Name of the variable. Optional.
Attributes
VariableName
(str) Name of the Variable.
VariableType
(CONTINUOUS or INTEGER) Variable type.
LB
(float) Lower Bound of the Variable.
UB
(float) Upper Bound of the Variable.
Obj
(float) Coefficient of the variable in the Objective function.
Value
(float) Value of the variable after solving.
ReducedCost
(float) Reduced Cost after solving an LP problem.
Methods
getIndex
()Get the index position of the variable in the problem.
Returns the lower bound of the variable.
Returns the objective coefficient of the variable.
Returns the upper bound of the variable.
getValue
()Returns the Value of the variable computed in current solution.
Returns the name of the variable.
Returns the type of the variable.
setLowerBound
(val)Sets the lower bound of the variable.
Sets the objective cofficient of the variable.
setUpperBound
(val)Sets the upper bound of the variable.
setVariableName
(val)Sets the name of the variable.
setVariableType
(val)Sets the variable type of the variable.
- getIndex()#
Get the index position of the variable in the problem.
- getLowerBound()#
Returns the lower bound of the variable.
- getObjectiveCoefficient()#
Returns the objective coefficient of the variable.
- getUpperBound()#
Returns the upper bound of the variable.
- getValue()#
Returns the Value of the variable computed in current solution. Defaults to 0
- getVariableName()#
Returns the name of the variable.
- getVariableType()#
Returns the type of the variable.
- setLowerBound(val)#
Sets the lower bound of the variable.
- setObjectiveCoefficient(val)#
Sets the objective cofficient of the variable.
- setUpperBound(val)#
Sets the upper bound of the variable.
- setVariableName(val)#
Sets the name of the variable.
- setVariableType(val)#
Sets the variable type of the variable. Variable types can be either CONTINUOUS or INTEGER.
- class cuopt.linear_programming.problem.LinearExpression(vars, coefficients, constant)#
Bases:
object
LinearExpressions contain a set of variables, the coefficients for the variables, and a constant. LinearExpressions can be used to create constraints and the objective in the Problem. LinearExpressions can be added and subtracted with other LinearExpressions and Variables and can also be multiplied and divided by scalars. LinearExpressions can be compared with scalars, Variables, and other LinearExpressions to create Constraints.
- Parameters:
- varsList
List of Variables in the linear expression.
- coefficientsList
List of coefficients corresponding to the variables.
- constantfloat
Constant of the linear expression.
Methods
Gets the coefficient of the variable at ith index of the linear expression.
Returns all the coefficients in the linear expression.
Returns the constant in the linear expression.
getValue
()Returns the value of the expression computed with the current solution.
getVariable
(i)Gets Variable at ith index in the linear expression.
Returns all the variables in the linear expression.
zipVarCoefficients
- getCoefficient(i)#
Gets the coefficient of the variable at ith index of the linear expression.
- getCoefficients()#
Returns all the coefficients in the linear expression.
- getConstant()#
Returns the constant in the linear expression.
- getValue()#
Returns the value of the expression computed with the current solution.
- getVariable(i)#
Gets Variable at ith index in the linear expression.
- getVariables()#
Returns all the variables in the linear expression.
- zipVarCoefficients()#
- class cuopt.linear_programming.problem.Constraint(expr, sense, rhs, name='')#
Bases:
object
cuOpt constraint object containing a linear expression, the sense of the constraint, and the right-hand side of the constraint. Constraints are associated with a problem and can be created using problem.addConstraint (See problem class).
- Parameters:
- exprLinearExpression
Linear expression corresponding to a problem.
- senseenum
Sense of the constraint. Either LE for <=, GE for >= or EQ for == .
- rhsfloat
Constraint right-hand side value.
- namestr, Optional
Name of the constraint. Optional.
Attributes
ConstraintName
(str) Name of the constraint.
Sense
(LE, GE or EQ) Row sense. LE for >=, GE for <= or EQ for == .
RHS
(float) Constraint right-hand side value.
Slack
(float) Computed LHS - RHS with current solution.
DualValue
(float) Constraint dual value in the current solution.
Methods
getCoefficient
(var)Returns the coefficient of a variable in the constraint.
Returns the name of the constraint.
getRHS
()Returns the right-hand side value of the constraint.
getSense
()Returns the sense of the constraint.
- getCoefficient(var)#
Returns the coefficient of a variable in the constraint.
- getConstraintName()#
Returns the name of the constraint.
- getRHS()#
Returns the right-hand side value of the constraint.
- getSense()#
Returns the sense of the constraint. Constraint sense can be LE(<=), GE(>=) or EQ(==).
- class cuopt.linear_programming.solution.solution.Solution(
- problem_category,
- vars,
- solve_time=0.0,
- primal_solution=None,
- dual_solution=None,
- reduced_cost=None,
- current_primal_solution=None,
- current_dual_solution=None,
- initial_primal_average=None,
- initial_dual_average=None,
- current_ATY=None,
- sum_primal_solutions=None,
- sum_dual_solutions=None,
- last_restart_duality_gap_primal_solution=None,
- last_restart_duality_gap_dual_solution=None,
- initial_primal_weight=0.0,
- initial_step_size=0.0,
- total_pdlp_iterations=0,
- total_pdhg_iterations=0,
- last_candidate_kkt_score=0.0,
- last_restart_kkt_score=0.0,
- sum_solution_weight=0.0,
- iterations_since_last_restart=0,
- termination_status=0,
- error_status=0,
- error_message='',
- primal_residual=0.0,
- dual_residual=0.0,
- primal_objective=0.0,
- dual_objective=0.0,
- gap=0.0,
- nb_iterations=0,
- solved_by_pdlp=None,
- mip_gap=0.0,
- solution_bound=0.0,
- presolve_time=0.0,
- max_constraint_violation=0.0,
- max_int_violation=0.0,
- max_variable_bound_violation=0.0,
- num_nodes=0,
- num_simplex_iterations=0,
A container of LP solver output
- Parameters:
- problem_categoryint
Whether it is a LP-0, MIP-1 or IP-2 solution
- varsDict[str, float64]
Dictionary mapping each variable (name) to its value.
- primal_solutionnumpy.array
Primal solution of the LP problem
- dual_solutionnumpy.array
Note: Applicable to only LP Dual solution of the LP problem
- reduced_costnumpy.array
Note: Applicable to only LP The reduced cost. It contains the dual multipliers for the linear constraints.
- termination_status: Integer
Termination status value.
- primal_residual: Float64
L2 norm of the primal residual: measurement of the primal infeasibility
- dual_residual: Float64
Note: Applicable to only LP L2 norm of the dual residual: measurement of the dual infeasibility
- primal_objective: Float64
Value of the primal objective
- dual_objective: Float64
Note: Applicable to only LP Value of the dual objective
- gap: Float64
Difference between the primal and dual objective
- nb_iterations: Int
Number of iterations the LP solver did before converging
- mip_gap: float64
Note: Applicable to only MILP The relative difference between the best integer objective value found so far and the objective bound. A value of 0.01 means the solution is guaranteed to be within 1% of optimal.
- solution_bound: float64
Note: Applicable to only MILP The best known bound on the optimal objective value. For minimization problems, this is a lower bound on the optimal value. For maximization problems, this is an upper bound.
- max_constraint_violation: float64
Note: Applicable to only MILP The maximum amount by which any constraint is violated in the current solution. Should be close to zero for a feasible solution.
- max_int_violation: float64
Note: Applicable to only MILP The maximum amount by which any integer variable deviates from being an integer. A value of 0 means all integer variables have integral values.
- max_variable_bound_violation: float64
Note: Applicable to only MILP The maximum amount by which any variable violates its upper or lower bounds in the current solution. Should be zero for a feasible solution.
- presolve_time: float64
Note: Applicable to only MILP Time used for pre-solve
- solve_time: Float64
Solve time in seconds
- solved_by_pdlp: bool
Whether the problem was solved by PDLP or Dual Simplex
Methods
Note: Applicable to only LP Returns the dual objective as a float64.
Note: Applicable to only LP Returns the dual solution as numpy.array with float64 type.
Returns the error message as per ErrorMessage.
Returns the error status as per ErrorStatus.
Note: Applicable to only LP Returns the convergence statistics as a dictionary:
Note: Applicable to only MILP Returns the convergence statistics as a dictionary:
Note: Applicable to only LP
Returns the primal objective as a float64.
Returns the primal solution as numpy.array with float64 type.
Returns one of the problem category from ProblemCategory
Returns the reduced cost as numpy.array with float64 type.
Returns the engine solve time in seconds as a float64.
Returns whether the problem was solved by PDLP or Dual Simplex
Returns the termination reason as per TerminationReason.
Returns the termination status as per TerminationReason.
get_vars
()Returns the dictionnary mapping each variable (name) to its value.
raise_if_lp_solution
raise_if_milp_solution
- raise_if_milp_solution(function_name)#
- raise_if_lp_solution(function_name)#
- get_primal_solution()#
Returns the primal solution as numpy.array with float64 type.
- get_dual_solution()#
Note: Applicable to only LP Returns the dual solution as numpy.array with float64 type.
- get_primal_objective()#
Returns the primal objective as a float64.
- get_dual_objective()#
Note: Applicable to only LP Returns the dual objective as a float64.
- get_termination_status()#
Returns the termination status as per TerminationReason.
- get_termination_reason()#
Returns the termination reason as per TerminationReason.
- get_error_status()#
Returns the error status as per ErrorStatus.
- get_error_message()#
Returns the error message as per ErrorMessage.
- get_solve_time()#
Returns the engine solve time in seconds as a float64.
- get_solved_by_pdlp()#
Returns whether the problem was solved by PDLP or Dual Simplex
- get_vars()#
Returns the dictionnary mapping each variable (name) to its value.
- get_lp_stats()#
Note: Applicable to only LP Returns the convergence statistics as a dictionary:
- “primal_residual”: float64
Measurement of the primal infeasibility. This quantity is being reduced until primal tolerance is met (see SolverSettings primal_tolerance).
- “dual_residual”: float64,
Measurement of the dual infeasibility. This quantity is being reduced until dual tolerance is met (see SolverSettings dual_tolerance).
- “gap”: float64
Difference between the primal and dual objective. This quantity is being reduced until gap tolerance is met (see SolverSettings gap_tolerance).
- “nb_iterations”: int
Number of iterations the LP solver did before converging.
- get_reduced_cost()#
Returns the reduced cost as numpy.array with float64 type.
- get_pdlp_warm_start_data()#
Note: Applicable to only LP
Allows to retrieve the warm start data from the PDLP solver.
See SolverSettings.set_pdlp_warm_start_data for more details.
- get_milp_stats()#
Note: Applicable to only MILP Returns the convergence statistics as a dictionary:
- mip_gap: float64
The relative difference between the best integer objective value found so far and the objective bound. A value of 0.01 means the solution is guaranteed to be within 1% of optimal.
- presolve_time: float64
Time took for pre-solve
- max_constraint_violation: float64
The maximum amount by which any constraint is violated in the current solution. Should be close to zero for a feasible solution .
- max_int_violation: float64
The maximum amount by which any integer variable deviates from being an integer. A value of 0 means all integer variables have integral values.
- max_variable_bound_violation: float64
The maximum amount by which any variable violates its upper or lower bounds in the current solution. Should be zero for a feasible solution.
- solution_bound: float64
The best known bound on the optimal objective value. For minimization problems, this is a lower bound on the optimal value. For maximization problems, this is an upper bound.
- num_nodes: int
Number of nodes explored during the MIP solve
- num_simplex_iterations: int
Number of simplex iterations performed during the MIP solve
- get_problem_category()#
Returns one of the problem category from ProblemCategory
LP - 0 MIP - 1 IP - 2