Skip to content

Commit

Permalink
use pkglite
Browse files Browse the repository at this point in the history
  • Loading branch information
wlandau-lilly committed Aug 8, 2023
1 parent 8def2d7 commit 561c4a2
Show file tree
Hide file tree
Showing 20 changed files with 725 additions and 12 deletions.
18 changes: 9 additions & 9 deletions README.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,14 @@ These instructions explain how to create an R package with pre-compiled Stan mod

Begin with an R package with one or more Stan model files inside the `inst/stan/` directory. `stan_package_create()` is a convenient way to start.

```{r}
```r
stan_package_create(path = "package_folder")
#> Example package named "example" created at "package_folder". Run stan_package_configure(path = "package_folder") so that the built-in Stan model will compile when the package installs.
```

At minimum the package file structure should look something like this:

```{r}
```r
fs::dir_tree("package_folder")
#> package_folder
#> ├── DESCRIPTION
Expand All @@ -128,11 +128,11 @@ fs::dir_tree("package_folder")

Configure the package so the Stan models compile during installation. `stan_package_configure()` writes scripts `configure` and `configure.win` for this, as well as `cleanup` and `cleanup.win` to remove compiled model files. Inside each script is a call to `instantiate::stan_package_compile()` which you can manually edit to control how your models are compiled. For example, different calls to `stan_package_compile()` can compile different groups of models using different C++ compiler flags.

```{r}
```r
stan_package_configure(path = "package_folder")
```

```{r}
```r
fs::dir_tree("package_folder")
#> package_folder
#> ├── DESCRIPTION
Expand All @@ -147,17 +147,17 @@ fs::dir_tree("package_folder")

## Installation

Install the package at `package_folder` just like you would any other R package.
Install the package just like you would any other R package. To install it from your local copy of `package_folder`, open R and run:

```{r}
install.packages("package_folder", type = "source", repos = NULL)
```r
install.packages(pkgs = "package_folder", type = "source", repos = NULL)
```

## Models

A user can now run a model from the package without any additional compilation. See the documentation of [`CmdStanR`](https://mc-stan.org/cmdstanr/index.html) to learn how to use [`CmdStanR`](https://mc-stan.org/cmdstanr/index.html) model objects.

```{r}
```r
library(example)
model <- stan_package_model(name = "bernoulli", package = "example")
print(model) # CmdStanR model object
Expand Down Expand Up @@ -199,7 +199,7 @@ fit$summary()

You can write an exported user-side function in your R package to access the model. For example, you might store this code in a `R/model.R` file in the package:

```{r}
```r
#' @title Fit the Bernoulli model.
#' @export
#' @family models
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,11 @@ fs::dir_tree("package_folder")

## Installation

Install the package at `package_folder` just like you would any other R
package.
Install the package just like you would any other R package. To install
it from your local copy of `package_folder`, open R and run:

``` r
install.packages("package_folder", type = "source", repos = NULL)
install.packages(pkgs = "package_folder", type = "source", repos = NULL)
```

## Models
Expand Down
10 changes: 10 additions & 0 deletions example.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
library(pkglite)
spec <- file_spec(
path = ".",
pattern = "*",
format = "text",
all_files = TRUE,
recursive = TRUE
)
collection <- collate(pkg = "example", spec)
pack(collection, output = "inst/example.txt", quiet = TRUE)
9 changes: 9 additions & 0 deletions example/.Rbuildignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
^.*\.Rproj$
^\.git$
^\.github$
^\.gitignore$
^\.Rbuildignore$
^\.RData$
^\.Rhistory$
^\.Rproj\.user$
^NOTICE$
51 changes: 51 additions & 0 deletions example/.github/workflows/check.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on: [push, pull_request]

name: check-internal

jobs:
check-internal:
runs-on: ${{ matrix.config.os }}

name: ${{ matrix.config.os }} (${{ matrix.config.r }})

strategy:
fail-fast: false
matrix:
config:
- {os: ubuntu-latest, r: 'release'}

env:
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
NOT_CRAN: true
R_KEEP_PKG_SOURCE: yes

steps:
- uses: actions/checkout@v3

- uses: r-lib/actions/setup-pandoc@v2

- uses: r-lib/actions/setup-r@v2
with:
r-version: ${{ matrix.config.r }}
extra-repositories: 'https://mc-stan.org/r-packages/'
http-user-agent: ${{ matrix.config.http-user-agent }}
use-public-rspm: true

- name: Install CmdStan
shell: Rscript {0}
run: |
install.packages("cmdstanr", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
cmdstanr::check_cmdstan_toolchain(fix = TRUE)
cmdstanr::install_cmdstan()
- uses: r-lib/actions/setup-r-dependencies@v2
with:
extra-packages: any::rcmdcheck, local::.
needs: check
cache-version: 2

- uses: r-lib/actions/check-r-package@v2
with:
upload-snapshots: true
10 changes: 10 additions & 0 deletions example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
*~
.Rapp.history
.RData
.Rhistory
.Rproj.user/
inst/stan/**
!inst/stan/**/*.*
inst/stan/**/*.exe
inst/stan/**/*.EXE
*.dll
18 changes: 18 additions & 0 deletions example/DESCRIPTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Package: example
Type: Package
Title: Example Package With Instantiate
Version: 0.0.1
Author: You
Maintainer: The package maintainer <yourself@somewhere.net>
Description: Demonstrate how to create an R package with pre-compiled Stan
models.
Depends:
R (>= 4.0.0)
Imports:
instantiate
Additional_repositories:
https://mc-stan.org/r-packages/
SystemRequirements: CmdStan (https://mc-stan.org/users/interfaces/cmdstan)
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.2.3
4 changes: 4 additions & 0 deletions example/NAMESPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Generated by roxygen2: do not edit by hand

export(run_bernoulli_model)
importFrom(instantiate,stan_package_model)
34 changes: 34 additions & 0 deletions example/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
This package includes components from other open-source software. The projects and licenses are listed below.

* CmdStan (https://github.com/stan-dev/cmdstan) by Stan Developers and their Assignees.

BSD 3-Clause License
=====================

Copyright (c) 2014, Stan
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
21 changes: 21 additions & 0 deletions example/R/model.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#' @title Fit the Bernoulli model.
#' @export
#' @family models
#' @description Fit the Bernoulli Stan model and return posterior summaries.
#' @return A data frame of posterior summaries.
#' @param y Numeric vector of Bernoulli observations (zeroes and ones).
#' @param `...` Named arguments to the `sample()` method of CmdStan model
#' objects: <https://mc-stan.org/cmdstanr/reference/model-method-sample.html>
#' @examples
#' if (instantiate::stan_cmdstan_exists()) {
#' run_bernoulli_model(y = c(1, 0, 1, 0, 1, 0, 0, 0, 0, 0))
#' }
run_bernoulli_model <- function(y, ...) {
stopifnot(is.numeric(y) && all(y >= 0 & y <= 1))
model <- instantiate::stan_package_model(
name = "bernoulli",
package = "example"
)
fit <- model$sample(data = list(N = length(y), y = y), ...)
fit$summary()
}
6 changes: 6 additions & 0 deletions example/R/package.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#' example: Example Package With Instantiate
#' @docType package
#' @name example-package
#' @family help
#' @importFrom instantiate stan_package_model
NULL
17 changes: 17 additions & 0 deletions example/example.Rproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Sweave
LaTeX: pdfLaTeX

BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
46 changes: 46 additions & 0 deletions example/inst/stan/bernoulli.stan
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* This model was borrowed from the CmdStan projec with the BSD 3-Clause License.
BSD 3-Clause License
=====================
Copyright (c) 2019, Stan Developers and their Assignees
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

data {
int<lower=0> N;
array[N] int<lower=0,upper=1> y;
}
parameters {
real<lower=0,upper=1> theta;
}
model {
theta ~ beta(1,1); // uniform prior on interval 0,1
y ~ bernoulli(theta);
}
7 changes: 7 additions & 0 deletions example/man/example-package.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions example/man/run_bernoulli_model.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 34 additions & 0 deletions inst/configuration/cleanup
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env sh
#
# This script was copied and modified from the source code of the {configure}
# R package by Kevin Ushey. License and copyright are in the comment below.
#
# MIT License
# =====================
#
# Copyright 2021 Kevin Ushey
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
: "${R_HOME=`R RHOME`}"
$R_HOME/bin/Rscript -e "instantiate::stan_package_clean()"
if [ $? -ne 0 ]; then
echo "Could not clean up compiled Stan models." >&2
exit 1
fi
exit 0
Loading

0 comments on commit 561c4a2

Please sign in to comment.