Documentation

Building the model

Building the model

The example now builds an optimization model. The data associated with an optimization model must be stored in a single list variable. Named components in this list contain the different parts of the model. The most fundamental named components are: The constraint matrix (A), the objective vector (obj), the right-hand side vector (rhs), and the constraint sense vector (sense). Among these, only the constraint matrix is mandatory, and default values are substituted for all other model fields in case they are missing. A model variable can also include optional components (e.g., the objective sense modelsense).

In our example, we use the built-in R matrix function to build the constraint matrix A. A is stored as a dense matrix here. You can also store A as a sparse matrix, using either the sparse_triplet_matrix function from the slam package or the sparseMatrix class from the Matrix package. Sparse input matrices are illustrated in the lp2.R example.

Subsequent statements populate other components of the model variable, including the objective vector, the right-hand-side vector, and the constraint sense vector. In each case, we use the built-in c function to initialize the array arguments.

In addition to the mandatory components, this example also sets two optional components: modelsense and vtype. The former is used to indicate the sense of the objective function. The default is minimization, so we've set the component equal to 'max' to indicate that we would like to maximize the specified objective. The vtype component is used to indicate the types of the variables in the model. In our example, all variables are binary ('B'). Note that our interface allows you to specify a scalar value for any array argument. The Gurobi interface will expand that scalar to a constant array of the appropriate length. In this example, the scalar value 'B' will be expanded to an array of length 3, containing one 'B' value for each column of A.

One important note about default variable bounds: the convention in math programming is that a variable will by default have a lower bound of 0 and an infinite upper bound. If you'd like your variables to have different bounds, you'll need to provide them explicitly.