knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

optplot

The goal of optplot is provide functions to plot optimization problems/models such as mixed-integer linear programs. Work in progress. Contributions welcome.

Travis build status lifecycle CRAN status

Installation

You can install the released version of optplot from CRAN with:

install.packages("optplot")

And the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("dirkschumacher/optplot")

Example

This is a basic example which shows you how to plot the popular Travling Salesperson Problem. It uses the ompr package to model the MILP.

# based on the Miller–Tucker–Zemlin (MTZ) formulation
# More info here: https://www.unc.edu/~pataki/papers/teachtsp.pdf)
library(ompr)
library(magrittr)
set.seed(1234)
n <- 10
model <- MILPModel() %>%
  # we create a variable that is 1 iff we travel from city i to j
  add_variable(x[i, j], i = 1:n, j = 1:n, 
               type = "integer", lb = 0, ub = 1) %>%

  # a helper variable for the MTZ formulation of the tsp
  add_variable(u[i], i = 1:n, lb = 1, ub = n) %>% 

  # minimize travel distance
  set_objective(sum_expr(colwise(runif(n^2)) * x[i, j], i = 1:n, j = 1:n), "min") %>%

  # you cannot go to the same city
  set_bounds(x[i, i], ub = 0, i = 1:n) %>%

  # leave each city
  add_constraint(sum_expr(x[i, j], j = 1:n) == 1, i = 1:n) %>%
  #
  # visit each city
  add_constraint(sum_expr(x[i, j], i = 1:n) == 1, j = 1:n) %>%

  # ensure no subtours (arc constraints)
  add_constraint(u[i] >= 2, i = 2:n) %>% 
  add_constraint(u[i] - u[j] + 1 <= (n - 1) * (1 - x[i, j]), i = 2:n, j = 2:n)

Having defined the model, we can extract the constraint matrix $A$, the right hand side vector $b$ and the objective coefficent vector $c$.

mat <- ompr::extract_constraints(model)
A <- mat$matrix
b <- mat$rhs
cv <- ompr::objective_function(model)$solution
optplot::milp_plot(A, b, cv)


dirkschumacher/optplot documentation built on May 5, 2019, 12:30 p.m.