---
title: "mirai - Parallel Integration"
vignette: >
  %\VignetteIndexEntry{mirai - Parallel Integration}
  %\VignetteEngine{litedown::vignette}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  out.width = "100%"
)
```
### Parallel Integration

`mirai` provides an alternative communications backend for R. This functionality was developed to fulfil a request by R Core at R Project Sprint 2023.

`make_cluster()` creates a cluster object of class 'miraiCluster', which is fully-compatible with `parallel` cluster types.

  + Specify 'n' to launch nodes on the local machine.
  + Specify 'url' for receiving connections from remote nodes.
  + Optionally, specify 'remote' to launch remote daemons using a remote configuration generated by `remote_config()` or `ssh_config()`.

Created clusters may be used for any function in the `parallel` base package such as `parallel::clusterApply()` or `parallel::parLapply()`, or the load-balanced versions such as `parallel::parLapplyLB()`.
```{r cluster}
library(mirai)

cl <- make_cluster(4)
cl
parallel::parLapply(cl, iris, mean)
```
```{r sleep, echo=FALSE}
Sys.sleep(1L)
```
`status()` may be called on a 'miraiCluster` to query the number of connected nodes at any time.
```{r cluster2}
status(cl)
stop_cluster(cl)
```
Making a cluster specifying 'url' without 'remote' causes the shell commands for manual deployment of nodes to be printed to the console.
```{r cluster3}
cl <- make_cluster(n = 2, url = host_url())
stop_cluster(cl)
```

### Foreach Integration

A 'miraiCluster' may also be registered by [`doParallel`](https://cran.r-project.org/package=doParallel) for use with the [`foreach`](https://cran.r-project.org/package=foreach) package.

Running some parallel examples for the `foreach()` function:

```{r foreach}
library(foreach)
library(iterators)

cl <- make_cluster(4)
doParallel::registerDoParallel(cl)

# normalize the rows of a matrix
m <- matrix(rnorm(9), 3, 3)
foreach(i = 1:nrow(m), .combine = rbind) %dopar%
  (m[i, ] / mean(m[i, ]))
# simple parallel matrix multiply
a <- matrix(1:16, 4, 4)
b <- t(a)
foreach(b = iter(b, by='col'), .combine = cbind) %dopar%
  (a %*% b)
```
