-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
87 lines (65 loc) · 2.56 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
---
output: github_document
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r setup, include = FALSE}
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](https://travis-ci.org/dirkschumacher/optplot.svg?branch=master)](https://travis-ci.org/dirkschumacher/optplot)
[![lifecycle](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental)
[![CRAN status](https://www.r-pkg.org/badges/version/optplot)](https://cran.r-project.org/package=optplot)
## Installation
You can install the released version of optplot from [CRAN](https://CRAN.R-project.org) with:
``` r
install.packages("optplot")
```
And the development version from [GitHub](https://github.com/) with:
``` r
# 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.
```{r example}
# 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$.
```{r}
mat <- ompr::extract_constraints(model)
A <- mat$matrix
b <- mat$rhs
cv <- ompr::objective_function(model)$solution
```
```{r milp-plot}
optplot::milp_plot(A, b, cv)
```