File: Introduction_To_BiocParallel.Rmd

package info (click to toggle)
r-bioc-biocparallel 1.40.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,768 kB
  • sloc: cpp: 139; sh: 14; makefile: 8
file content (865 lines) | stat: -rw-r--r-- 28,029 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
---
title: "1. Introduction to *BiocParallel*"
author:
- name: "Valerie Obenchain"
- name: "Vincent Carey"
- name: "Michael Lawrence"
- name: "Phylis Atieno"
  affiliation: "Vignette translation from Sweave to Rmarkdown / HTML"
- name: "Martin Morgan"
  email: "Martin.Morgan@RoswellPark.org"
date: "Edited: October, 2022; Compiled: `r format(Sys.time(), '%B %d, %Y')`"
package: BiocParallel
vignette: >
  %\VignetteIndexEntry{1. Introduction to BiocParallel}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
output:
  BiocStyle::html_document
---

# Introduction

Numerous approaches are available for parallel computing in R. The
CRAN Task View for high performance and parallel computing provides
useful high-level summaries and [package
categorization](https://cran.r-project.org/web/views/HighPerformanceComputing.html).
Most Task View packages cite or identify one or more of
[*snow*](https://cran.r-project.org/package=snow) ,
[*Rmpi*](https://cran.r-project.org/package=Rmpi),
[*multicore*](https://cran.r-project.org/package=multicore) or
[*foreach*](https://cran.r-project.org/package=foreach) as relevant
parallelization infrastructure. Direct support in *R* for *parallel*
computing started with release 2.14.0 with inclusion of the
[parallel](https://cran.r-project.org/package=parallel) package which
contains modified versions of
[*multicore*](https://cran.r-project.org/package=multicore) and
[*snow*](https://cran.r-project.org/package=snow).

A basic objective of [*BiocParallel*][] is to reduce the complexity
faced when developing and using software that performs parallel
computations. With the introduction of the `BiocParallelParam` object,
[*BiocParallel*][] aims to provide a unified interface to existing
parallel infrastructure where code can be easily executed in different
environments. The `BiocParallelParam` specifies the environment of
choice as well as computing resources and is invoked by 'registration'
or passed as an argument to the [*BiocParallel*][] functions.

[*BiocParallel*][] offers the following conveniences over the 'roll
your own' approach to parallel programming.

- unified interface: `BiocParallelParam` instances define the method
  of parallel evaluation (multi-core, snow cluster, etc.) and
  computing resources (number of workers, error handling, cleanup,
  etc.).

- parallel iteration over lists, files and vectorized operations:
  `bplapply`, `bpmapply` and `bpvec` provide parallel list iteration
  and vectorized operations. `bpiterate` iterates through files
  distributing chunks to parallel workers.

- cluster scheduling: When the parallel environment is managed by a
  cluster scheduler through
  [*batchtools](https://cran.r-project.org/package=batchtools), job
  management and result retrieval are considerably simplified.

- support of `foreach` : The
  [*foreach*](https://cran.r-project.org/package=foreach) and
  [*iterators*](https://cran.r-project.org/package=iterators) packages
  are fully supported. Registration of the parallel back end uses
  `BiocParallelParam` instances.

# Quick start


The [*BiocParallel*][] package is available at bioconductor.org and
can be downloaded via `BiocManager`:

```
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("BiocParallel")
```

Load [*BiocParallel*][]

```{r}
library(BiocParallel)
```

The test function simply returns the square root of "x".

```{r quick_start FUN}
FUN <- function(x) { round(sqrt(x), 4) }
```

Functions in [*BiocParallel*][] use the registered back-ends for
parallel evaluation. The default is the top entry of the registry
list.

```{r quick_start registry}
registered()
```

Configure your R session to always use a particular back-end configure
by setting options named after the back ends in an `.RProfile` file,
e.g.,

```{r configure_registry, eval=FALSE}
options(MulticoreParam=MulticoreParam(workers=4))
```

When a [*BiocParallel*][] function is invoked with no `BPPARAM`
argument the default back-end is used.

```{r quickstart_bplapply_default, eval=FALSE}
bplapply(1:4, FUN)
```

Environment specific back-ends can be defined for any of the registry
entries. This example uses a 2-worker SOCK cluster.

```{r quickstart_snow}
param <- SnowParam(workers = 2, type = "SOCK")
bplapply(1:4, FUN, BPPARAM = param)
```

# The *BiocParallel* Interface

## Classes

### `BiocParallelParam`

`BiocParallelParam` instances configure different parallel evaluation
environments. Creating or `register()` ing a '`Param`' allows the same
code to be used in different parallel environments without a code
re-write. Params listed are supported on all of Unix, Mac and Windows
except `MulticoreParam` which is Unix and Mac only.

- `SerialParam`:

  Supported on all platforms.

  Evaluate [*BiocParallel*][]-enabled code with parallel evaluation
  disabled. This approach is useful when writing new scripts and
  trying to debug code.

- `MulticoreParam`:

  Supported on Unix and Mac. On Windows, `MulticoreParam` dispatches
  to `SerialParam`.

  Evaluate [*BiocParallel*][]-enabled code using multiple cores on a
  single computer.  When available, this is the most efficient and
  least troublesome way to parallelize code. Windows does not
  support multi-core evaluation (the `MulticoreParam` object can be
  used, but evaluation is serial). On other operating systems, the
  default number of workers equals the value of the global option
  `mc.cores` (e.g.,`getOption("mc.cores")` ) or, if that is not set,
  the number of cores returned by `arallel::detectCores() - 2` ;
  when number of cores cannot be determined, the default is 1.

  `MulticoreParam` uses 'forked' processes with 'copy-on-change'
  semantics -- memory is only copied when it is changed. This makes
  it very efficient to invoke compared to other back-ends.

  There are several important caveats to using
  `MulticoreParam`. Forked processes are not available on
  Windows. Some environments, e.g., *RStudio*, do not work well with
  forked processes, assuming that code evaluation is
  single-threaded. Some external resources, e.g., access to files or
  data bases, maintain state in a way that assumes the resource is
  accessed only by a single thread. A subtle cost is that *R*'s
  garbage collector runs periodically, and 'marks' memory as in
  use. This effectively triggers a copy of the marked memory. *R*'s
  generational garbage collector is triggered at
  difficult-to-predict times; the effect in a long-running forked
  process is that the memory is eventually copied. See [this
  post](https://support.bioconductor.org/p/70196/#70509) for
  additional details.

  `MulticoreParam` is based on facilities originally implemented in
  the [*multicore*](https://cran.r-project.org/package=multicore)
  package and subsequently the
  [*parallel*](https://cran.r-project.org/package=parallel) package
  in base.

- `SnowParam`:

  Supported on all platforms.

  Evaluate [*BiocParallel*][]-enabled code across several distinct
  instances, on one or several computers. This is a straightforward
  approach for executing parallel code on one or several computers,
  and is based on facilities originally implemented in the
  [*snow*](https://cran.r-project.org/package=snow)
  package. Different types of
  [*snow*](https://cran.r-project.org/package=snow) 'back-ends' are
  supported, including socket and MPI clusters.

- `BatchtoolsParam`:

  Applicable to clusters with formal schedulers.

  Evaluate [*BiocParallel*][]-enabled code by submitting to a
  cluster scheduler like SGE.

- `DoparParam`:

  Supported on all platforms.

  Register a parallel back-end supported by the
  [*foreach*](https://cran.r-project.org/package=foreach) package
  for use with [*BiocParallel*][].

The simplest illustration of creating `BiocParallelParam` is

```{r BiocParallelParam_SerialParam}
serialParam <- SerialParam()
serialParam
```

Most parameters have additional arguments influencing behavior, e.g.,
specifying the number of 'cores' to use when creating a
`MulticoreParam` instance

```{r BiocParallelParam_MulticoreParam}
multicoreParam <- MulticoreParam(workers = 8)
multicoreParam
```

Arguments are described on the corresponding help page, e.g.,
`?MulticoreParam.`.

### `register()`ing `BiocParallelParam` instances

The list of registered `BiocParallelParam` instances represents the
user's preferences for different types of back-ends. Individual
algorithms may specify a preferred back-end, and different back-ends
maybe chosen when parallel evaluation is nested.

The registry behaves like a 'stack' in that the last entry registered
is added to the top of the list and becomes the "next used" (i.e., the
default).

`registered` invoked with no arguments lists all back-ends.

```{r register_registered}
registered()
```

`bpparam` returns the default from the top of the list.

```{r register_bpparam}
bpparam()
```

Add a specialized instance with `register`. When `default` is TRUE,
the new instance becomes the default.

```{r register_BatchtoolsParam}
default <- registered()
register(BatchtoolsParam(workers = 10), default = TRUE)
```

`BatchtoolsParam` has been moved to the top of the list and is now the
default.

```{r register_BatchtoolsParam2}
names(registered())
bpparam()
```

Restore the original registry

```{r register_restore}
for (param in rev(default))
    register(param)
```

## Functions


### Parallel looping, vectorized and aggregate operations

These are used in common functions, implemented as much as possible for
all back-ends. The functions (see the help pages, e.g., `?bplapply` for a full
definition) include

`bplapply(X, FUN, ...)`:

Apply in parallel a function `FUN` to each element of `X`. `bplapply`
invokes `FUN length(X)` times, each time with a single element of `X`.

`bpmapply(FUN, ...)`:

Apply in parallel a function to the first, second, etc., elements of
each argument in ....

`bpiterate(ITER, FUN, ...)`:

Apply in parallel a function to the output of function `ITER`. Data
chunks are returned by `ITER` and distributed to parallel workers
along with `FUN`. Intended for iteration though an undefined number of
data chunks (i.e., records in a file).

`bpvec(X, FUN, ...)`:

Apply in parallel a function `FUN` to subsets of `X`.`bpvec` invokes
function as many times as there are cores or cluster nodes, with
receiving a subset (typically more than 1 element, in contrast to
`bplapply`) of `X`.

`bpaggregate(x, data, FUN, ...)`:

Use the formula in `X` to aggregate `data` using `FUN`.

### Parallel evaluation environment

These functions query and control the state of the parallel evaluation
environment.

`bpisup(x)`: Query a `BiocParallelParam` back-end `X` for its status.

`bpworkers`; `bpnworkers`: Query a `BiocParallelParam` back-end for
the number of workers available for parallel evaluation.

`bptasks`: Divides a job (e.g., single call to \*lapply function) into
tasks.  Applicable to `MulticoreParam` only;`DoparParam` and
`BatchtoolsParam` have their own approach to dividing a job among
workers.

`bpstart(x)`: Start a parallel back end specified by
`BiocParallelParam x, `, if possible.

`bpstop(x)`: Stop a parallel back end specified by `BiocParallelParam x`.

### Error handling and logging

Logging and advanced error recovery is available in `BiocParallel`
1.1.25 and later.  For a more details see the vignette titled "Error
Handling and Logging":

```{r error-vignette, eval=FALSE}
browseVignettes("BiocParallel")
```

### Locks and counters

Inter-process (i.e., single machine) locks and counters are supported
using `ipclock()`, `ipcyield()`, and friends. Use these to synchronize
computation, e.g., allowing only a single process to write to a file
at a time.

# Use cases

Sample data are BAM files from a transcription profiling experiment
available in the *RNAseqData.HNRNPC.bam.chr14* package.

```{r use_cases_data}
library(RNAseqData.HNRNPC.bam.chr14)
fls <- RNAseqData.HNRNPC.bam.chr14_BAMFILES
```

## Single machine

Common approaches on a single machine are to use multiple cores in
forked processes, or to use clusters of independent processes.

For purely -based computations on non-Windows computers, there are
substantial benefits, such as shared memory, to be had using forked
processes. However, this approach is not portable across platforms,
and fails when code uses functionality, e.g., file or data base
access, that assumes only a single thread is accessing the
resource. While use of forked processes with `MulticoreParam` is an
attractive solution for scripts using pure functionality, robust and
complex code often requires use of independent processes and
`SnowParam`.

### Forked processes with `MulticoreParam`

This example counts overlaps between BAM files and a defined set of
ranges. First create a GRanges with regions of interest (in practice
this could be large).

```{r forking_gr, message=FALSE}
library(GenomicAlignments) ## for GenomicRanges and readGAlignments()
gr <- GRanges("chr14", IRanges((1000:3999)*5000, width=1000))
```

A `ScanBamParam` defines regions to extract from the files.

```{r forking_param}
param <- ScanBamParam(which=range(gr))
```

`FUN` counts overlaps between the ranges in 'gr' and the files.

```{r forking_FUN}
FUN <- function(fl, param) {
    gal <- readGAlignments(fl, param = param)
    sum(countOverlaps(gr, gal))
}
```

All parameters necessary for running a job in a multi-core environment
are specified in the `MulticoreParam` instance.

```{r forking_default_multicore}
MulticoreParam()
```

The [*BiocParallel*][] functions, such as `bplapply`, use information
in the `MulticoreParam` to set up the appropriate back-end and pass
relevant arguments to low-level functions.

```{verbatim}
> bplapply(fls[1:3], FUN, BPPARAM = MulticoreParam(), param = param)
$ERR127306
[1] 1185

$ERR127307
[1] 1123

$ERR127308
[1] 1241
```

Shared memory environments eliminate the need to pass large data
between workers or load common packages. Note that in this code the
GRanges data was not passed to all workers in `bplapply` and FUN did
not need to load
[*GenomicAlignments*[](http://bioconductor.org/packages/GenomicAlignments)for
access to the `readGAlign ments` function.

Problems with forked processes occur when code implementating
functionality used by the workers is not written in anticipation of use
by forked processes. One example is the database connection underlying
Bioconductor's `org.*` packages. This pseudo-code

```{r db_problems, eval = FALSE}
library(org.Hs.eg.db)
FUN <- function(x, ...) {
...
mapIds(org.Hs.eg.db, ...)
...
}
bplapply(X, FUN, ..., BPPARAM = MulticoreParam())
```

is likely to fail, because `library(org.Hs.eg.db)` opens a database
connection that is accessed by multiple processes. A solution is to
ensure that the database is opened independently in each process

```
FUN <- function(x, ...) {
library(org.Hs.eg.db)
...
mapIds(org.Hs.eg.db, ...)
...
}
bplapply(X, FUN, ..., BPPARAM = MulticoreParam())
```

### Clusters of independent processes with `SnowParam`

Both Windows and non-Windows machines can use the cluster approach to
spawn processes. [*BiocParallel*][] back-end choices for clusters on a
single machine are *SnowParam* for configuring a Snow cluster or the
*DoparParam* for use with the *foreach* package.

To re-run the counting example, FUN needs to modified such that 'gr'
is passed as a formal argument and required libraries are loaded on
each worker. (In general, this is not necessary for functions defined
in a package name space, see [Section 6](#sec:developers).)

```{r cluster_FUN}
FUN <- function(fl, param, gr) {
    suppressPackageStartupMessages({
        library(GenomicAlignments)
    })
    gal <- readGAlignments(fl, param = param)
    sum(countOverlaps(gr, gal))
}
```

Define a 2-worker SOCK Snow cluster.

```{r cluster_snow_param}
snow <- SnowParam(workers = 2, type = "SOCK")
```

A call to `bplapply` with the *SnowParam* creates the cluster and
distributes the work.

```{r cluster_bplapply}
bplapply(fls[1:3], FUN, BPPARAM = snow, param = param, gr = gr)
```

The FUN written for the cluster adds some overhead due to the passing
of the GRanges and the loading of
[*GenomicAlignments*](http://bioconductor.org/packages/GenomicAlignments)
on each worker. This approach, however, has the advantage that it
works on most platforms and does not require a coding change when
switching between windows and non-windows machines.

If several `bplapply()` statements are likely to require the same
resource, it often makes sense to create a cluster once using
`bpstart()`. The workers are re-used by each call to `bplapply()`, so
they do not have to re-load packages, etc.

```{r db_solution_2, eval = FALSE}
register(SnowParam()) # default evaluation
bpstart() # start the cluster
...
bplapply(X, FUN1, ...)
...
bplapply(X, FUN2, ...) # re-use workers
...
bpstop()
```

## *Ad hoc* cluster of multiple machines

We use the term *ad hoc* cluster to define a group of machines that can
communicate with each other and to which the user has password-less
log-in access. This example uses a group of compute machines (\"the
rhinos\") on the FHCRC network.

### *Ad hoc* Sockets

On Linux and Mac OS X, a socket cluster is created across machines by
supplying machine names as the`workers``argument to a
*BiocParallelParam* instance instead of a number. Each name represents
an *R* process; repeat names indicate multiple workers on the same
machine.

Create a with *SnowParam* 2 cpus from 'rhino01' and 1 from 'rhino02'.

```
hosts <- c("rhino01", "rhino01", "rhino02")
param <- SnowParam(workers = hosts, type = "SOCK")
```

Execute FUN 4 times across the workers.

```{verbatim}
> FUN <- function(i) system("hostname", intern=TRUE)
> bplapply(1:4, FUN, BPPARAM = param)
[[1]]
[1] "rhino01"

[[2]]
[1] "rhino01"

[[3]]
[1] "rhino02"

[[4]]
[1] "rhino01"
```

When creating a cluster across Windows machines must be IP addresses
(e.g., \"140.107.218.57\") instead of machine names.

 ### MPI

An MPI cluster across machines is created with *mpirun* or *mpiexec*
from the command line or a script. A list of machine names provided as
the -hostfile argument defines the mpi universe.

The hostfile requests 2 processors on 3 different machines.

```{verbatim}
rhino01 slots=2
rhino02 slots=2
rhino03 slots=2
```

From the command line, start a single interactive process on the current
machine.

```{verbatim}
mpiexec --np 1 --hostfile hostfile R --vanilla
```

Load [*BiocParallel*][] and create an MPI Snow cluster. The number
`workers` of in should match the number of slots requested in the
hostfile. Using a smaller number of workers uses a subset of the
slots.

```{verbatim}
> library(BiocParallel)
> param <- SnowParam(workers = 6, type = "MPI")
```

Execute FUN 6 times across the workers.

```{verbatim}
> FUN <- function(i) system("hostname", intern=TRUE)
> bplapply(1:6, FUN, BPPARAM = param)
bplapply(1:6, FUN, BPPARAM = param)
[[1]]
[1] "rhino01"

[[2]]
[1] "rhino02"

[[3]]
[1] "rhino02"

[[4]]
[1] "rhino03"

[[5]]
[1] "rhino03"

[[6]]
[1] "rhino01"
```

Batch jobs can be launched with mpiexec and R CMD BATCH. Code to be
executed is in 'Rcode.R'.

```{verbatim}
mpiexec --hostfile hostfile R CMD BATCH Rcode.R
```

## Clusters with schedulers

Computer clusters are far from standardized, so the following may
require significant adaptation; it is written from experience here at
FHCRC, where we have a large cluster managed via SLURM. Nodes on the
cluster have shared disks and common system images, minimizing
complexity about making data resources available to individual nodes.
There are two simple models for use of the cluster, Cluster-centric and
R-centric.

### Cluster-centric

The idea is to use cluster management software to allocate resources,
and then arrange for an script to be evaluated in the context of
allocated resources. NOTE: Depending on your cluster configuration it
may be necessary to add a line to the template file instructing workers
to use the version of R on the master / head node. Otherwise the default
R on the worker nodes will be used.

For SLURM, we might request space for 4 tasks (with `salloc` or
`sbatch`), arrange to start the MPI environment (with `orterun`) and on
a single node in that universe run an script `BiocParallel-MPI.R`. The
command is

```{verbatim}
$ salloc -N 4 orterun -n 1 R -f BiocParallel-MPI.R
```

The *R* script might do the following, using MPI for parallel evaluation.
Start by loading necessary packages and defining `FUN` work to be done

```{r cluster-MPI-work, eval=FALSE}
library(BiocParallel)
library(Rmpi)
FUN <- function(i) system("hostname", intern=TRUE)
```

Create a *SnowParam* instance with the number of nodes equal to the
size of the MPI universe minus 1 (let one node dispatch jobs to
workers), and register this instance as the default

```{r cluster-MPI, eval=FALSE}
param <- SnowParam(mpi.universe.size() - 1, "MPI")
register(param)
```

Evaluate the work in parallel, process the results, clean up, and quit

```{r cluster-MPI-do, eval=FALSE}
xx <- bplapply(1:100, FUN)
table(unlist(xx))
mpi.quit()
```

The entire session is as follows:

```{verbatim}
$ salloc -N 4 orterun -n 1 R --vanilla -f BiocParallel-MPI.R
salloc: Job is in held state, pending scheduler release
salloc: Pending job allocation 6762292
salloc: job 6762292 queued and waiting for resources
salloc: job 6762292 has been allocated resources
salloc: Granted job allocation 6762292
## ...
> FUN <- function(i) system("hostname", intern=TRUE)
>
> library(BiocParallel)
> library(Rmpi)
> param <- SnowParam(mpi.universe.size() - 1, "MPI")
> register(param)
> xx <- bplapply(1:100, FUN)
> table(unlist(xx))
gizmof13 gizmof71 gizmof86 gizmof88
25 25 25 25
>
> mpi.quit()
salloc: Relinquishing job allocation 6762292
salloc: Job allocation 6762292 has been revoked.
```

One advantage of this approach is that the responsibility for managing
the cluster lies firmly with the cluster management software -- if one
wants more nodes, or needs special resources, then adjust parameters
to `salloc` (or `sbatch`).

Notice that workers are spawned within the `bplapply` function; it
might often make sense to more explicitly manage workers with
`bpstart` and `bpstop`, e.g.,

```{r cluster-MPI-bpstart, eval=FALSE}
param <- bpstart(SnowParam(mpi.universe.size() - 1, "MPI"))
register(param)
xx <- bplapply(1:100, FUN)
bpstop(param)
mpi.quit()
```

### R-centric

A more *R*-centric approach might start an *R* script on the head
node, and use *batchtools* to submit jobs from within *R* the
session. One way of doing this is to create a file containing a
template for the job submission step, e.g., for SLURM; a starting
point might be found at

```{r slurm}
tmpl <- system.file(package="batchtools", "templates", "slurm-simple.tmpl")
noquote(readLines(tmpl))
```

The *R* script, run interactively or from the command line, might then
look like

```{r cluster-batchtools, eval=FALSE}
## define work to be done
FUN <- function(i) system("hostname", intern=TRUE)
library(BiocParallel)

## register SLURM cluster instructions from the template file
param <- BatchtoolsParam(workers=5, cluster="slurm", template=tmpl)
register(param)

## do work
xx <- bplapply(1:100, FUN)
table(unlist(xx))
```

The code runs on the head node until `bplapply` , where the script
interacts with the SLURM scheduler to request a SLURM allocation, run
jobs, and retrieve results.  The argument `4` to `BatchtoolsParam`
specifies the number of workers to request from the scheduler;
`bplapply` divides the 100 jobs among the 4 workers. If
`BatchtoolsParam` had been created without specifying any workers,
then 100 jobs implied by the argument to `bplapply` would be
associated with 100 tasks submitted to the scheduler.

Because cluster tasks are running in independent `R` instances, and
often on physically separate machines, a convenient 'best practice' is
to write `FUN` in a 'functional programming' manner, such that all
data required for the function is passed in as arguments or (for large
data) loaded implicitly or explicitly (e.g., via an *R* library) from
disk.

# Analyzing genomic data in *Bioconductor*


General strategies exist for handling large genomic data that are well
suited to *R* programs. A manuscript titled *Scalable Genomics with R
and BioConductor* (<http://arxiv.org/abs/1409.2864>) by Michael
Lawrence and Martin Morgan, reviews several of these approaches and
demonstrate implementation with *Bioconductor * packages. Problem
areas include scalable processing, summarization and
visualization. The techniques presented include restricting queries,
compressing data, iterating, and parallel computing.

Ideas are presented in an approachable fashion within a framework of
common use cases. This is a benificial read for anyone anyone tackling
genomics problems in *R*.

# For developers {#sec:developers}


Developers wishing to use [*BiocParallel*][] in their own packages
should include [*BiocParallel*][] in the `DESCRIPTION` file

```{verbatim}
Imports: BiocParallel
```

and import the functions they wish to use in the `NAMESPACE` file,
e.g.,

```{verbatim}
importFrom(BiocParallel, bplapply)
```

Then invoke the desired function in the code, e.g.,

```{r devel-bplapply}
system.time(x <- bplapply(1:3, function(i) { Sys.sleep(i); i }))

unlist(x)
```

This will use the back-end returned by `bpparam()` , by default a
`MulticoreParam()` on Linux / macOS, on Windows, or the user's
preferred back-end if they have used `register()`.

The `MulticoreParam` back-end does not require any special
configuration or set-up and is therefore the safest option for
developers. Unfortunately, `MulticoreParam` provides only serial
evaluation on Windows.

Developers should document that their function uses [*BiocParallel*][]
functions on the main page, and should perhaps include in their
function signature an argument `BPPARAM=bpparam()`.  Developers should
NOT use 'register()' in package code -- this sets a preference that
influences use of 'bplapply()' and friends in all packages, not just
their package.

Developers wishing to invoke back-ends other than `MulticoreParam` ,
or to write code that works across Windows, macOS and Linux, no longer
need to take special care to ensure that required packages, data, and
functions are available and loaded on the remote nodes. By default,
will export global variables to the workers due to the
default. Nonetheless, a good practice during development is to use
independent processes (via ) rather than relying on forked (via )
processes. For instance, clusters include the costs of setting up the
computational environment (loading required packages, for instance)
that may discourage use of parallelization when parallelization
provides only marginal performance gains from the computation *per
se*. Likewise, may be more sensitive to inappropriate calls to shared
libraries, revealing errors that are only transient under.

In `bplapply()`, the environment of `FUN` (other than the global
environment) is serialized to the workers. A consequence is that, when
`FUN ` is inside a package name space, other functions available in
the name space are available to `FUN ` on the workers.

# For server administrators {#sec:administrators}

If the package is installed on a server used by multiple users, then the
default value of cores used can sometimes lead to many more tasks being
run than the server has cores if two or more users run a
parallel-enabled function simultaneously. A more conservative number of
cores than all of them minus 2 may be desirable, so that one user does
not take all of the cores unless they explicitly specify so. This can be
implemented with environment variables. Setting or for all system users
to the number of cores divided by the typical number of concurrent users
is a reasonable approach to avoiding this scenario.

# sessionInfo

```{r sessionInfo}
sessionInfo()
```

[*BiocParallel*]: https://bioconductor.org/packages/BiocParallel