---
title: "Gurobi Installation Guide"
author: "Richard Schuster"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: true
    fig_caption: true
    self_contained: yes
fontsize: 11pt
documentclass: article
vignette: >
  %\VignetteIndexEntry{Gurobi Installation Guide}
  %\VignetteEngine{knitr::rmarkdown_notangle}
---

```{r, include = FALSE}
h = 3.5
w = 3.5
is_check <- ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_",
             "_R_CHECK_LICENSE_") %in% names(Sys.getenv()))
knitr::opts_chunk$set(fig.align = "center", eval = !is_check)
```

```{r, include = FALSE}
devtools::load_all()
```

## Introduction

Gurobi is the most powerful and fastest solver that _prioritizr_ can use to solve conservation planning problems. This vignette will walk you through the process of setting up Gurobi on your computer. If you encounter any problems while following the instructions below, check out the [official Gurobi documentation](http://www.gurobi.com/documentation/) or the [official Gurobi emailing list](https://groups.google.com/forum/#!forum/gurobi) for more information.

## Obtaining a license

One of the potential caveats associated with using Gurobi that you will need to obtain a [license](http://www.gurobi.com/products/licensing-pricing/licensing-overview). If you are an academic that is affiliated with an educational institution, you can take advantage of the [special academic license](https://user.gurobi.com/download/licenses/free-academic) to use Gurobi for no cost. Once you have signed up for a free account you can request a [free academic license](https://www.gurobi.com/registration/academic-license-reg).

<br><center>![](figures/free-academic-license-page.png){ width=75% }</center><br>

Once you accept the terms of service you can generate a license.

<br><center>![](figures/actual-license.png){ width=75% }</center><br>

Now, copy and save the `grbgetkey XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX` command for later use.

## Software installation

The Gurobi software installation itself is platform specific. You will need to [download the version that works for your operating system ](http://www.gurobi.com/downloads/gurobi-optimizer). The [documentation page](http://www.gurobi.com/documentation/) and platform specific "Quick Start Guides" should help you with the installation. [On Windows, simply download the installer and follow the prompts.](http://www.gurobi.com/documentation/7.5/quickstart_windows/software_installation_guid.html#section:Installation) [On Linux, you will need to download an archive containing Gurobi, extract its contents, move them them to a suitable location, and update your system's variables.](http://www.gurobi.com/documentation/7.5/quickstart_linux/software_installation_guid.html).

Additionally, if you are using [RStudio](https://www.rstudio.com/products/rstudio/) on a Linux system, you might need to add the following line to the file _/etc/rstudio/rserver.conf_:

```
rsession-ld-library-path=/opt/gurobi650/linux64/lib
```

After installing the Gurobi software suite on your computer, you will need to activate your license.

## License activation

Now we will activate the Gurobi software using the license you downloaded earlier. To achieve this, simply copy and paste the `grbgetkey` command into your computer's command prompt or terminal. After running the `grbgetkey` command with the correct license code, you should see output that looks like the screen shot below.

<br><center>![](figures/cmd-windows-success.png){ width=75% }</center><br>

We can double check that the license has been successfully activated by running Gurobi from the command line. Assuming you have installed Gurobi version 7.5.1, Windows users can type in the following the following commands:

```
gurobi_cl c:\gurobi751\win64\examples\data\coins.lp
```

Additionally, Linux users can test their license activation using the following commands

```
gurobi_cl /opt/gurobi751/linux64/examples/data/coins.lp
```

If the license was successfully activated, you should seen an output that looks like the screen shot below.

<br><center>![](figures/model-test.png){ width=75% }</center><br>

After activating the license, you now need to install the Gurobi _R_ package named _gurobi_.

## _R_ package installation

We need to install the Gurobi _R_ package named _gurobi_ to use Gurobi from within _R_. The _gurobi_ _R_ package installation file can be found within the folder where you installed Gurobi. Assuming you installed Gurobi in the default location, Windows users can install _gurobi_ _R_ package by running the following code from within _R_:

```{r, eval = FALSE}
install.packages("c:/gurobi751/win64/R/gurobi_7.5-1.zip", repos = NULL)
```

Additionally, Linux users can install the _gurobi_ _R_ package by running the following code from within R:

```{r, eval = FALSE}
install.packages(file.path(Sys.getenv("GUROBI_HOME"), "R/gurobi_7.5-1.zip"),
                 repos = NULL)
```

Next, you will need to install the _slam_ package because the _gurobi_ _R_ package needs this package to work. Both Windows and Linux users can do this by running the code below in _R_:

```{r, eval  = FALSE}
install.packages("slam", repos = "https://cloud.r-project.org")
```

Let's check that the _gurobi_ _R_ package is installed correctly. To do this, you can try using Gurobi to solve an optimization problem using the _R_ code below.

```{r}
# load gurobi package
library(gurobi)

# create optimization problem
model <- list()
model$obj        <- c(1, 1, 2)
model$modelsense <- "max"
model$rhs        <- c(4, 1)
model$sense      <- c("<", ">")
model$vtype      <- "B"
model$A          <- matrix(c(1, 2, 3, 1, 1, 0), nrow = 2, ncol = 3,
                           byrow = TRUE)

# solve the optimization problem using Gurobi
result <- gurobi(model, list())

# print the solution
print(result$objval) # objective
print(result$x)      # decision variables
```

If you don't see any error messages, then you have successfully installed Gurobi and can now use it with _prioritizr_. If do see an error message, then you probably missed a step while installing the package or activating the license.

## Solving a _prioritzr_ problem with Gurobi

If you successfully installed Gurobi software and the _gurobi_ _R_ package, you can now try using Gurobi to solve reserve selection problems using the _prioritzr_ _R_ package. Although the _prioritizr_ _R_ package should automatically detect that Gurobi has been installed, you can use the function [`add_gurobi_solver`](https://prioritizr.github.io/prioritizr/reference/add_gurobi_solver.html) to customize the optimization process.

Finally, to check that everything has been installed correctly, we will use Gurobi to solve a reserve selection problem created using the _prioritzr_ _R_ package.

```{r, fig.height = h, fig.width = w}
library(prioritizr)

# formulate the problem
p <- problem(sim_pu_raster, sim_features) %>%
      add_min_set_objective() %>%
      add_relative_targets(0.1) %>%
      add_gurobi_solver()

# solve the problem
s <- solve(p)

# plot solution
plot(s, col = c("grey90", "darkgreen"), main = "Solution",
     xlim = c(-0.1, 1.1), ylim = c(-0.1, 1.1))
```

If you have managed run the code on your system without encountering any errors, then you have correctly installed Gurobi and can begin using it to solve your very own conservation planning problems.
