ompr Fundamentals
This document is prepared as both a quick introduction and future reference (or cheat sheet) for the ompr package. Full documentation can be found in here.
Model building
In ompr, we start by defining the model with MIPModel(). Then we will append a combination of the below commands with either one of the pipes %>% or |> (for the sake of consistency we will use only one pipe type in a single code block).
add_variableis used to add the variables. Its properties aretype(“continuous”,“binary” or “integer”),ub(upper bound),lb(lower bound). It is possible to add index to the variable. (see reference)- For instance,
add_variable(x[i],i=1:10)will create a set of 10 decision variables. - It is also possible to have multiple dimensions.
add_variable(x[i,j],i=1:10, j=1:3)will create a set of 30 decision variables.
- For instance,
add_constraintis used to add constraints. It is possible to add expressions directly (e.g.,2x + y <= 5). It is also possible to add indices for repetitions of the constraint. (see reference)set_objectiveis used to set the objective function and its direction (or sense). Objective function can be directly written as an expression. Sense should be either"max"or"min". (see reference)
Solving
After defining the model we solve the model with solve_model() command. We can define a solver. In this document, we will use HiGHS solver. Therefore command will be solve_model(with_ROI(solver = "highs",verbose=TRUE)) most of the time.
Getting results
If the model is run successfully we will get a response. Let’s assume we store model response in model_obj variable. Then we will be able to query the model for results.