---
title: "Get Started with sims"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Get Started with sims}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

sims is an R package to generate datasets from [JAGS](https://mcmc-jags.sourceforge.io/) or R code for use in simulation studies.

## Simulating as `nlists` Objects

By default, `sims_simulate()` returns the simulated datasets in the form of an [nlists](https://github.com/poissonconsulting/nlist) object.

```{r example}
library(sims)
set.seed(10)
sims_simulate("a <- runif(1)", nsims = 2L)
```

## Saving as `.rds` Files

If, however, `save = TRUE` then each nlist object is saved as an `.rds` file in `path`.
```{r}
set.seed(10)
sims_simulate("a <- runif(1)", nsims = 2L, save = TRUE, path = tempdir(), exists = NA)
sims_data_files(tempdir())
```

### Importing `.rds` Files

The datasets in the `.rds` files can be imported as an `nlists` object using `sims_data()`.
```{r}
sims_data(tempdir())
```

### Adding `.rds` Files

The values including the `.Random.seed` (not printed) that were used to generate the datasets are saved in `.sims_args.rds` which can be imported using `sims_info()`.

```{r}
sims_info(tempdir())[1:5]
```

The fact that the arguments to `sims_simulate()` are saved to file allows additional `.rds` datasets to be generated using `sims_add()`.
```{r}
sims_add(tempdir(), nsims = 3L)
sims_data_files(tempdir())
```

### Copying `.rds` Files

If the user wishes to duplicate the datasets then they can either regenerate them by specifying a different path but the same seed (using `set.seed()`).
Alternatively, they can copy the existing `.sims.rds` and datasets files to a new directory using `sims_copy()`
```{r}
sims_copy(path_from = tempdir(), path_to = paste0(tempdir(), "_copy"))
```

### Checking `.rds` Files

A user can check that all the datasets specified in `.sims.rds` are present using `sims_check()`.
```{r}
sims_check(path = paste0(tempdir(), "_copy"))
```

```{r, error = TRUE}
file.remove(file.path(paste0(tempdir(), "_copy"), "data0000005.rds"))

sims_check(path = paste0(tempdir(), "_copy"))
```

```{r, echo = FALSE}
unlink(paste0(tempdir(), "_copy"), recursive = TRUE, force = TRUE) # required to clean up detritus
```

## Parallelization

Parallelization is implemented using the [future](https://github.com/HenrikBengtsson/future) package.

To use all available cores on the local machine simply execute the following code before calling `sims_simulate()`.
```{r}
library(future)
plan(multisession)
```

```{r}
set.seed(10)
sims_simulate("a <- runif(1)", nsims = 2L)
```

## Progress

Progress is reported using the [progressr](https://github.com/HenrikBengtsson/progressr) package as follows.

```{r}
library(progressr)
with_progress(sims_simulate("a <- runif(1)", nsims = 1000L))
```
