---
title: "Save Models to Local Disk"
author: 
  - name: Shixiang Wang
    affiliation: Central South University
    email: wangshx@csu.edu.cn
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Save Models to Local Disk}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  out.width = "100%"
)
qs2_available <- requireNamespace("qs2", quietly = TRUE) &&
  requireNamespace("ids", quietly = TRUE)
```

```{r setup}
library(bregr)
```

Two global options have been introduced to control whether models are saved as local files (`bregr.save_model`, default is `FALSE`) and where they should be saved (`bregr.path`, default uses a temporary path).

```{r, eval = qs2_available}
options(bregr.save_model = TRUE)
# Set model save path if necessary
# options(bregr.path = "/model/to/path")

m <- breg(mtcars) |>
  br_set_y("mpg") |>
  br_set_x(colnames(mtcars)[2:4]) |>
  br_set_x2("vs") |>
  br_set_model("gaussian") |>
  br_run()

options(bregr.save_model = FALSE)
```

In summary, the models have been saved to a unique path. We can verify this by examining the model objects:

```{r, eval = qs2_available}
m@models
```

We can retrieve the saved models using the following commands:

```{r, eval = qs2_available}
br_get_models(m, 1)
br_get_models(m, c(1, 3))
br_get_models(m, "cyl")
br_get_models(m, c("cyl", "hp"))
br_get_models(m)
```

The modeling results should remain consistent, regardless of whether they are saved or not.

Run without saving models.

```{r, eval = qs2_available}
m2 <- breg(mtcars) |>
  br_set_y("mpg") |>
  br_set_x(colnames(mtcars)[2:4]) |>
  br_set_x2("vs") |>
  br_set_model("gaussian") |>
  br_run()
m2@models
```

```{r, eval = qs2_available}
all.equal(m, m2)
```

