An open API service indexing awesome lists of open source software.

https://github.com/dirkschumacher/optplot

An R package for plotting optimization problems/models
https://github.com/dirkschumacher/optplot

mixed-integer-programming plot r visualization

Last synced: 9 months ago
JSON representation

An R package for plotting optimization problems/models

Awesome Lists containing this project

README

          

---
output: github_document
---

```{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)
```