Skip to content

Commit be1b097

Browse files
committed
Using checkmate for input validation, drop whole package import of rlang, input validation doc.
1 parent e4e0000 commit be1b097

54 files changed

Lines changed: 870 additions & 1732 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

DESCRIPTION

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ License: GPL (>= 3)
99
URL: https://kylesnap.github.io/ernest/
1010
BugReports: https://github.com/kylesnap/ernest/issues/
1111
Imports:
12+
checkmate,
1213
cli,
1314
generics,
1415
ggplot2,
@@ -19,14 +20,14 @@ Imports:
1920
R6,
2021
rlang (>= 1.1.0),
2122
tibble,
22-
tidyselect,
2323
utils,
2424
vctrs
2525
Suggests:
2626
ggdist,
2727
knitr,
2828
LaplacesDemon,
2929
rmarkdown,
30+
tidyselect,
3031
testthat (>= 3.0.0),
3132
vdiffr,
3233
xml2

NAMESPACE

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@ export(nested_sampling)
4343
export(rwmh_cube)
4444
export(unif_cube)
4545
export(visualize)
46-
import(rlang)
4746
importFrom(R6,R6Class)
4847
importFrom(cli,cli_abort)
4948
importFrom(cli,cli_progress_bar)
@@ -70,11 +69,28 @@ importFrom(lifecycle,deprecated)
7069
importFrom(posterior,as_draws)
7170
importFrom(posterior,as_draws_matrix)
7271
importFrom(posterior,as_draws_rvars)
73-
importFrom(rlang,"%@%")
74-
importFrom(rlang,"%@%<-")
7572
importFrom(rlang,"%|%")
7673
importFrom(rlang,"%||%")
74+
importFrom(rlang,.data)
75+
importFrom(rlang,arg_match)
76+
importFrom(rlang,arg_match0)
77+
importFrom(rlang,as_function)
78+
importFrom(rlang,call2)
79+
importFrom(rlang,caller_arg)
80+
importFrom(rlang,caller_env)
81+
importFrom(rlang,check_dots_empty)
82+
importFrom(rlang,check_dots_used)
83+
importFrom(rlang,expr)
84+
importFrom(rlang,exprs)
85+
importFrom(rlang,inject)
7786
importFrom(rlang,is_double)
87+
importFrom(rlang,is_empty)
88+
importFrom(rlang,is_scalar_double)
89+
importFrom(rlang,is_scalar_integerish)
90+
importFrom(rlang,is_scalar_logical)
91+
importFrom(rlang,list2)
92+
importFrom(rlang,new_function)
93+
importFrom(rlang,pairlist2)
7894
importFrom(rlang,try_fetch)
7995
importFrom(tibble,tibble)
8096
importFrom(utils,head)

R/as_draws.R

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,16 @@
33
#' Try to transform an [ernest_run-class] to a format supported by the
44
#' [posterior][posterior::posterior-package] package.
55
#'
6-
#' @param x An `ernest_run` object.
7-
#' @inheritParams rlang::args_dots_empty
8-
#' @param units Character string specifying the scale of the returned points.
9-
#' One of `"original"` or `"unit_cube"`, case sensitive.
10-
#' - `"original"`: Points are expressed on the scale of the prior space.
11-
#' - `"unit_cube"`: Points are expressed on the scale of the (0-1)-unit
6+
#' @param x (ernest_run) An `ernest_run` object.
7+
#' @param units (case-sensitive string) The scale in which to return the
8+
#' sampled points:
9+
#' * `"original"`: Points are expressed on the scale of the prior space.
10+
#' * `"unit_cube"`: Points are expressed on the scale of the (0-1)-unit
1211
#' hypercube.
13-
#' @param radial Whether to return an additional column `.radial`, containing
14-
#' the radial coordinate (i.e., the squared sum of squares) for each sampled
15-
#' point.
12+
#' @param radial (logical) Whether to return an additional column `.radial`,
13+
#' containing the radial coordinate (i.e., the squared sum of squares) for
14+
#' each sampled point.
15+
#' @inheritParams rlang::args_dots_empty
1616
#'
1717
#' @returns
1818
#' A [draws][posterior::as_draws()] object, containing the posterior samples
@@ -87,27 +87,21 @@ as_draws_rvars.ernest_run <- function(
8787

8888
#' Convert samples to a weighted draws matrix
8989
#'
90-
#' @param x An object containing sample data, with `samples`, `samples_unit`,
91-
#' `log_weight`, and `log_evidence` components.
92-
#' @param ... Currently unused. For future extensibility.
93-
#' @param units Character string specifying the units for conversion.
94-
#' Must be one of `"original"` or `"unit_cube"`.
95-
#' @param radial Logical. If `TRUE`, appends a `.radial` column with the
96-
#' Euclidean norm of each sample.
90+
#' @inheritParams as_draws_matrix
9791
#' @param error_call Environment to use for error reporting.
98-
#'
99-
#' @srrstats {G2.3, G2.3a} Using `arg_match` to validate character input.
92+
#'
93+
#' @srrstats {G2.3, G2.3a} Using `arg_match` to validate character input.
10094
#'
10195
#' @return A weighted draws matrix of class `draws_matrix`.
10296
#' @noRd
103-
as_draws_matrix_ <- function(x, ..., units, radial, error_call = caller_env()) {
104-
check_dots_empty(call = error_call)
97+
as_draws_matrix_ <- function(x, ..., units, radial, call = caller_env()) {
98+
check_dots_empty(call = call)
10599
units <- arg_match0(
106100
units,
107101
values = c("original", "unit_cube"),
108-
error_call = error_call
102+
error_call = call
109103
)
110-
check_bool(radial, error_call = error_call)
104+
radial <- as_scalar_logical(radial, call = call)
111105

112106
points <- if (units == "original") x$samples else x$samples_unit
113107
if (radial) {

R/calculate.R

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
#' Estimate Evidence using a Nested Sampling Run
22
#'
3-
#' @param x An `ernest_run` object.
3+
#' @param x (ernest_run) An `ernest_run` object.
44
#' @inheritParams rlang::args_dots_empty
5-
#' @param ndraws A positive integer or a boolean. If `FALSE`, the log volumes
6-
#' will be derived from their expected values. If not `FALSE`, the log volumes
7-
#' will be simulated using `ndraws` samples from each volume's
8-
#' joint distribution.
5+
#' @param ndraws (positive integer or zero, optional) The number of log volume
6+
#' sequences to simulate. If equal to zero, no simulations will be made, and a
7+
#' one draw vector of log volumes are produced from the estimates contained in
8+
#' `x`. If `NULL`, `getOption("posterior.rvar_ndraws")` is used (default 4000).
99
#'
1010
#' @returns A tibble, containing `run$n_iter + run$n_points` rows and the
1111
#' following columns:
@@ -52,12 +52,12 @@
5252
#'
5353
#' @method calculate ernest_run
5454
#' @export
55-
calculate.ernest_run <- function(x, ..., ndraws = FALSE) {
55+
calculate.ernest_run <- function(x, ..., ndraws = NULL) {
5656
check_dots_empty()
57-
if (is.logical(ndraws)) {
58-
ndraws <- as.integer(ndraws)
59-
}
60-
ndraws <- check_integer(ndraws, min = 0)
57+
ndraws <- as_scalar_count(
58+
ndraws %||% getOption("posterior.rvar_ndraws", 4000L),
59+
positive = FALSE
60+
)
6161

6262
if (ndraws == 0) {
6363
return(tibble::new_tibble(

R/compile.R

Lines changed: 63 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,41 @@
33
#' Create a new set of live points/particles for a new nested sampling run, or
44
#' check the current state of the live points before continuing a previous run.
55
#'
6-
#' @param object An object of class `ernest_sampler`.
6+
#' @param object (ernest_sampler) An object of class `ernest_sampler`.
77
#' @inheritParams rlang::args_dots_empty
8-
#' @param seed Either a single value, interpretted as an integer, or `NA` or
9-
#' `NULL`.
10-
#' * If an integer or NULL, `seed` is passed to [set.seed()] to set the state
11-
#' of the random number generator. `NULL` reinitializes the generator as if
8+
#' @param seed (integer or NA, optional) Specification for the random number
9+
#' generator.
10+
#' * integer: Passed to [set.seed()].
11+
#' * `NULL`: Passed to [set.seed()], which reinitializes the generator as if
1212
#' no seed has yet been set.
13-
#' * If `NA`, the random number generator is set with the seed stored in the
14-
#' `ernest_run` object bound to `object`. If this object does not exist (i.e.,
15-
#' if not prior runs have been performed), the current state of the generator
16-
#' is recorded and stored for future objects.
17-
#' @param clear A logical value indicating whether to reload `object` before
18-
#' creating new live points. If `TRUE`, former results from the sampler are
19-
#' removed from the object. If `FALSE`, the sampler will not drop prior results,
20-
#' and continue using live points from the last sampling iteration performed.
13+
#' * `NA`: Make no changes to the current seed if set. If `compile` has been
14+
#' called on `object` before, then `NA` will ensure that the seed remain
15+
#' identical between runs.
16+
#' @param clear (boolean) Whether to reset the sampler before compiling.
17+
#' * `TRUE`: Previous results stored in `object` are removed, and live points
18+
#' are generated and validated.
19+
#' * `FALSE`: Previous results stored in `object` are retained, and live points
20+
#' are validated.
2121
#'
2222
#' @details
2323
#' The `compile` function prepares an `ernest_sampler` object for nested
2424
#' sampling by ensuring that its set of live points is valid and ready for use.
25-
#' In addition to constructing the live point set for new runs, the live points
26-
#' are validated for a number of conditions:
25+
#' In addition to constructing the live point set for new runs or when
26+
#' `clear = FALSE`, compile also ensures that:
2727
#'
28-
#' * Ensures that the points are each represented within the unit hypercube.
29-
#' * Ensures that the wrapped likelihood function `ernest_likelihood` has a
30-
#' valid return value for each point (finite double or `-Inf`).
31-
#' * Ensures that the likelihood isn't at a plateau, warning you if there are
32-
#' duplicate likelihood values.
28+
#' * The live points are each represented within the unit hypercube.
29+
#' * The wrapped likelihood function `ernest_likelihood` has a valid return
30+
#' value for each point (either a finite double or `-Inf`).
31+
#' * The live points don't represent a perfect plateau (i.e., all points share
32+
#' the same likelihood). You are warned if more than 25% of the points
33+
#' share the same likelihood value.
3334
#'
34-
#' If `compile` fails these validation steps, the function will fail and the
35-
#' set of live points will be removed from `object` with an informative error
36-
#' message encouraging you to run the sampler from scratch with `clear = TRUE`.
35+
#' If `compile` fails these validation steps, the set of live points will be
36+
#' removed from `object`, preventing you from calling [generate()] on a
37+
#' malformed sampler.
38+
#'
39+
#' Random number generation can be seeded either through the `seed` argument,
40+
#' or by calling [set.seed()] before running `compile` or `generate`.
3741
#'
3842
#' @returns `object`, invisibly.
3943
#' @examples
@@ -67,7 +71,7 @@ compile.ernest_sampler <- function(object, ..., seed = NA, clear = FALSE) {
6771
#' @return A list containing `unit`, `point`, and `log_lik` matrices/vectors.
6872
#' @noRd
6973
create_live <- function(lrps, n_points, call = caller_env()) {
70-
rlang::try_fetch(
74+
try_fetch(
7175
lrps$propose_uniform(criteria = rep(-1e300, n_points)),
7276
error = function(cnd) {
7377
cli::cli_abort(
@@ -100,64 +104,59 @@ create_live <- function(lrps, n_points, call = caller_env()) {
100104
#' NULL.
101105
#' @noRd
102106
check_live <- function(unit, log_lik, n_points, n_var, call = caller_env()) {
103-
# Check live point matrix.
104-
if (!is.numeric(unit) || !is.matrix(unit)) {
105-
stop_input_type(unit, "a numeric matrix", call = call)
106-
}
107-
if (ncol(unit) != n_var || nrow(unit) != n_points) {
108-
cli::cli_abort(
109-
c(
110-
"Live points matrix must have dim. {n_points} x {n_var}.",
111-
"x" = "Points are currently {nrow(unit)} x {ncol(unit)}."
112-
),
113-
call = call
114-
)
115-
}
116-
if (!all(is.finite(unit))) {
117-
cli::cli_abort(
118-
"Live points matrix must only contain finite values.",
119-
call = call
120-
)
107+
# Check live point matrix using checkmate.
108+
msg <- checkmate::check_matrix(
109+
unit,
110+
mode = "numeric",
111+
nrows = n_points,
112+
ncols = n_var,
113+
any.missing = FALSE,
114+
all.missing = FALSE
115+
)
116+
if (!isTRUE(msg)) {
117+
format_checkmate(msg, "unit", call = call)
121118
}
122-
if (any(unit < 0 | unit > 1)) {
123-
cli::cli_abort(
124-
"Live points matrix must only contain values between 0 and 1.",
125-
call = call
126-
)
119+
msg <- checkmate::check_numeric(
120+
unit,
121+
lower = 0,
122+
upper = 1,
123+
any.missing = FALSE,
124+
all.missing = FALSE,
125+
finite = TRUE
126+
)
127+
if (!isTRUE(msg)) {
128+
format_checkmate(msg, "unit", call = call)
127129
}
128130

129-
if (!is_double(log_lik, n = n_points)) {
130-
cli::cli_abort(
131-
c(
132-
"`log_lik` must be a double vector of length {n_points}",
133-
"!" = "You provided {obj_type_friendly(log_lik)}."
134-
),
135-
call = call
136-
)
131+
msg <- checkmate::check_numeric(
132+
log_lik,
133+
len = n_points,
134+
any.missing = FALSE,
135+
all.missing = FALSE
136+
)
137+
if (!isTRUE(msg)) {
138+
format_checkmate(msg, "log_lik", call = call)
137139
}
138140
if (any(!is.finite(log_lik) & log_lik != -Inf)) {
139-
n_nonfinite <- sum(!is.finite(log_lik) & log_lik != -Inf)
140-
cli::cli_abort(
141-
c(
142-
"Live points' log-likelihoods must be finite or -Inf.",
143-
"x" = "Found {n_nonfinite} non-finite values."
144-
),
141+
nonfinite <- unique(log_lik[!is.finite(log_lik) & log_lik != -Inf])
142+
cli_abort(
143+
"`{log_lik}` must contain only finite values or -Inf, not {nonfinite}.",
145144
call = call
146145
)
147146
}
148147

149148
n_unique <- vctrs::vec_unique_count(log_lik)
150149
if (n_unique == 1L) {
151-
cli::cli_abort(
150+
cli_abort(
152151
c(
153152
"Log likelihoods of the live points must not be a plateau.",
154-
"x" = "Log likelihood of all {n_points} points = {log_lik[1]}."
153+
"!" = "Log likelihood of all {n_points} points = {log_lik[1]}."
155154
),
156155
call = call
157156
)
158157
}
159158
if (n_unique < (n_points * 0.75)) {
160-
cli::cli_warn(
159+
cli_warn(
161160
c(
162161
"Potential likelihood plateau; proceed with caution.",
163162
"!" = "{n_unique} unique likelihoods across {n_points} live points."

R/ernest-package.R

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,9 @@
22
"_PACKAGE"
33

44
## usethis namespace: start
5-
#' @import rlang
65
#' @importFrom generics generate
76
#' @importFrom glue glue
87
#' @importFrom lifecycle deprecated
9-
#' @importFrom rlang %@%
10-
#' @importFrom rlang %@%<-
11-
#' @importFrom rlang %|%
12-
#' @importFrom rlang %||%
138
#' @importFrom tibble tibble
149
#' @importFrom utils head
1510
#' @importFrom utils tail

0 commit comments

Comments
 (0)