---
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 the _prioritizr R_ package can use to solve conservation planning problems. This vignette will walk you through the process of setting up _Gurobi_ on your computer so that you can use it to solve conservation planning problems. If you encounter any problems while following the instructions below, check out the [official _Gurobi_ documentation](http://www.gurobi.com/documentation/).

## Obtaining a license

_Gurobi_ is a commercial computer program. [This means that users will need to obtain a license for _Gurobi_ before they can use it](http://www.gurobi.com/products/licensing-pricing/licensing-overview). Although academics can obtain a special license at no cost, individuals that are not affiliated with a recognized educational institution may need to purchase a license to use _Gurobi_. If you are an academic that is affiliated with an educational institution, you can take advantage of the [special academic license](https://www.gurobi.com/downloads/end-user-license-agreement-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/downloads/end-user-license-agreement-academic/).

<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.

## Downloading the _Gurobi_ software suite

After obtaining a license, you will need to download a copy of the _Gurobi_ installer to your computer. To achieve this, visit the [_Gurobi_ downloads web page](http://www.gurobi.com/downloads/gurobi-optimizer) and download the correct version of the installer for your operating system.

## Software installation

The installation process for the _Gurobi_ software suite depends on the type of operating system you have installed on your computer. Fortunately, _Gurobi_ provide platform-specific ["Quick Start Guides"](http://www.gurobi.com/documentation/) for [Windows](http://www.gurobi.com/documentation/8.1/quickstart_windows/software_installation_guid.html#section:Installation), [Mac OSX](http://www.gurobi.com/documentation/8.1/quickstart_mac/software_installation_guid.html), and [Linux](http://www.gurobi.com/documentation/8.1/quickstart_linux/software_installation_guid.html) systems that should help with this. Briefly, on Windows systems, you just need to double-click on the _Gurobi_ installer, follow the prompts, and the installer will take care of rest. Whereas, on Linux systems, you will need to manually extract the downloaded file's contents to a folder, move the extracted contents to a suitable location (typically _/opt/gurobi_), and update your system's variables so that it knows where to find _Gurobi_. 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 located at _/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. Please note that the correct set of instructions depends on your system and license. In most cases, you should follow the instructions in the "Local license activation". If, and only if, you are activating a special Academic license on a networked computer that is not connected to your university's network (e.g. a cloud-based system), then please follow the instructions below in the "Cloud license activation over SSH" section.

### Local license activation

To activate the license, simply copy and paste the `grbgetkey` command into your computer's command prompt or terminal (note that Windows users can open the command prompt by typing `cmd` in the search box and pressing the `enter` key). After running the `grbgetkey` command with the correct license code, you should see output that looks something like that in the screen shot below.

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

### Cloud license activation over SSH

If you are activating a special Academic license on a networked system that is not connected to your university's network (e.g. a cloud-based server on [Amazon EC2](https://aws.amazon.com/ec2/) or [NeCTAR](https://nectar.org.au/)), then you will need to use the following instructions. Here, you will need a local computer that is connected to your university's network. For brevity, we will refer to your local computer as _COMPUTER1_ and your networked system where upon you wish to activate the _Gurobi_ license as _COMPUTER2_. We will also assume that your are running Ubuntu (14.04+) on both systems. The following instructions were adapted from a discussion thread on the [official _Gurobi_ emailing list](https://groups.google.com/forum/#!topic/gurobi/MaEP4cun8o8).

First, we will connect to _COMPUTER2_ using _COMPUTER1_. Here, we will use _USER.COMPUTER2_ to refer to the user name of your account on _COMPUTER2_, and _IP.COMPUTER2_ to refer to the IP address of _COMPUTER2_. If you do not know the IP address of _COMPUTER2_, you should be able to find it on the website where you launched the system. To connect to _COMPUTER2_ from _COMPUTER1_, type the following command into a new terminal session. Note that you may be prompted to enter a password.

```{bash, eval = FALSE}
ssh USER.COMPUTER2@IP.COMPUTER2
```

Next, we will install `sshserver` on _COMPUTER2_. To do this, enter the following command into the same terminal session.

```{bash, eval = FALSE}
sudo apt-get install openssh-server
```

Next, we will execute the following on command on _COMPUTER2_ to tell it to connect to _COMPUTER1_ when attempting to activate the _Gurobi_ license. Similar to before, we will use _USER.COMPUTER1_ to refer to the user name of your account _COMPUTER1_, and _IP.COMPUTER1_ to refer to the IP address of _COMPUTER1_. If you do not know the IP address of _COMPUTER1_, try visiting this website (https://whatismyipaddress.com) to find out what it is. Also note that your university might automatically block incoming SSH connections, so if you are unable to connect to _COMPUTER1_ from _COMPUTER2_ you may need to enlist the help of a member of your university's IT support team.

```{bash, eval = FALSE}
ssh -L 8080:apps.gurobi.com:80 USER.COMPUTER1@IP.COMPUTER1
```

Now, we will **open up another session** on _COMPUTER1_, connect to _COMPUTER2_ from _COMPUTER1_ using the same SSH command as before, and then tell _COMPUTER2_ to activate the license. Please replace `XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX` with the correct license activation code that you saved earlier (note that the `--http` flag may not be required for _Gurobi_ versions earlier than 8.0.0).

```{bash, eval = FALSE}
ssh USER.COMPUTER2@IP.COMPUTER2
grbgetkey --http --server=127.0.0.1 --port=8080 --verbose XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
```

Finally, after having activated the license, we can terminate our SSH connections and close the bash sessions.

### Verification

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

```{bash, eval = FALSE}
gurobi_cl c:\gurobi800\win64\examples\data\coins.lp
```

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

```{bash, eval = FALSE}
gurobi_cl /opt/gurobi800/linux64/examples/data/coins.lp
```

If the license was successfully activated, you should see output that looks something like that in 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

Now we will install the _gurobi R_ package distributed with the _Gurobi_ software suite. The _gurobi_ _R_ package installation file should be located within the folder where you installed the _Gurobi_ software suite. Assuming you installed _Gurobi_ in the default location and assuming you installed version 8.0.0, Windows users can install _gurobi_ _R_ package by running the following code from within _R_:

```{r, eval = FALSE}
install.packages("c:/gurobi800/win64/R/gurobi_8.0-0.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_8.0-0_R_x86_64-pc-linux-gnu.tar.gz"),
                 repos = NULL)
```

Next, you will need to install the _slam R_ 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 has been successfully installed. To do this, we can try using the _gurobi R_ package to solve an optimization problem. Copy and paste the _R_ code below into _R_.

```{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 see the outputs for `result$objval` and `result$x` and you don't see any error messages, then you have (1) successfully installed the _Gurobi_ software suite, (2) activated a valid license, and (3) successfully installed the _gurobi R_ package. Now you can finally use _Gurobi_ to solve conservation planning problems with _prioritizr_. If do see an error message, then you might have missed a step while installing the package or activating the license, so try going back through this vignette to see if you missed something.

## Solving a _prioritzr_ problem with _Gurobi_

If you successfully installed the _Gurobi_ software suite and the _gurobi_ _R_ package, you can now try solving conservation planning 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` to manually specify that _Gurobi_ should be used to solve problems. This function is also useful because you can use it to customize the optimization process (e.g. specify the desired optimality gap or set a limit on how much time should be spent searching for a solution).

Finally, to check that everything has been installed correctly, we will use the _Gurobi_ software suite 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))
```

After running this code, hopefully, you should some information printed on-screen about the optimization process and _R_ should produce a map displaying a solution. If this code does not produce any errors, then you have successfully installed everything and can begin using _Gurobi_ and the _prioritizr R_ package to solve your very own conservation planning problems.
