---
title: "Parallel computation"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Parallel computation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
<style>
body {
text-align: justify}
</style>
```{r, echo = FALSE, eval=TRUE, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
options(knitr.table.format = "html", rmarkdown.html_vignette.check_title = FALSE)

library(eRTG3D)
set.seed(123)
```

The computationally most intense functions `qProb.3d()`, `n.sim.cond.3d()` and `reproduce.track.3d()` of the package are also implemented in a parallel version. On Unix systems this is done using a fork cluster. On Windows systems PSOCK cluster is used.

Definition of start conditions and parameters:

```{r eval=FALSE, echo=FALSE, fig.height=5, fig.width=7, include=FALSE}
niclas <- track.properties.3d(niclas)
sim.locs <- nrow(niclas)
f <- 1500
a0 = niclas$a[1]
g0 = niclas$g[1]
```

Get movement characteristics (`P`) from the example trajectory and simulate a Unconditional Eprircal Random Walk (UERW) in order to extract the attraction term (`Q`):

```{r eval=FALSE}
P <- get.track.densities.3d(niclas, heightDistEllipsoid = TRUE, DEM = dem)
uerw <- sim.uncond.3d(sim.locs*f, start = c(niclas$x[1], niclas$y[1], niclas$z[1]), 
                      a0 = a0, g0 = g0, densities = P)
```

The parallel version of the `qProb.3d()` function can be accessed by setting the parameter `parallel = TRUE`:

```{r eval=FALSE, fig.height=5, fig.width=7}
Q <- qProb.3d(uerw, sim.locs, parallel = TRUE)
cerwList <- reproduce.track.3d(n.sim = 100, niclas, DEM = dem, parallel = TRUE)
```

And also for `n.sim.uncond.3d()`:

```{r eval=FALSE, fig.height=5, fig.width=7, quiet = TRUE}
cerwList <- n.sim.cond.3d(n.sim = 100, sim.locs, start=start, end=end,a0 = a0, g0 = g0,
                      densities=P, qProbs=Q, DEM = dem, parallel = TRUE)
```

Alternativly the number of nodes in the cluster can be specified by passing a number to the function: `parallel = 4`. In this case a fork or PSOCK cluster with 4 nodes will be used. The maximum number of nodes is not allowed to be larger than the number of available cores (Hyper Threading included).

```{r eval=FALSE, fig.height=5, fig.width=7, quiet = TRUE}
cerwList <- n.sim.cond.3d(n.sim = 100, sim.locs, start=start, end=end,a0 = a0, g0 = g0,
                      densities=P, qProbs=Q, DEM = dem, parallel = 4)
```

**Note:** If only a few tracks are simulated and the track length is short `sim.locs < 30`, then it is faster in many cases to stay with the single core version of the function, especially on Windows systems, where setting up clusters takes some time.
