|
| 1 | +#' Registry for parametrised probability distributions |
| 2 | +#' |
| 3 | +#' @description |
| 4 | +#' The DistributionRegistry manages and generates parameterized samplers for a |
| 5 | +#' variety of probability distributions. Common distributions are included by |
| 6 | +#' default, and more can be added. |
| 7 | +#' |
| 8 | +#' Once defined, you can create sampler objects for each distribution - |
| 9 | +#' individually (`create`) or in batches (`create_batch`) - and then easily |
| 10 | +#' draw random samples from these objects. |
| 11 | +#' |
| 12 | +#' To add more built-in distributions, edit `initialize()`. To add custom ones |
| 13 | +#' at any time, use `register()`. |
| 14 | +#' |
| 15 | +#' @docType class |
| 16 | +#' @importFrom R6 R6Class |
| 17 | +#' @export |
| 18 | + |
| 19 | +DistributionRegistry <- R6Class("DistributionRegistry", list( # nolint: object_name_linter |
| 20 | + |
| 21 | + #' @field registry Named list of registered distribution generator functions. |
| 22 | + registry = list(), |
| 23 | + |
| 24 | + #' @description |
| 25 | + #' Pre-registers a set of common base R distribution generators. |
| 26 | + initialize = function() { |
| 27 | + self$register("exponential", function(mean) { |
| 28 | + function(size = 1L) rexp(size, rate = 1L / mean) |
| 29 | + }) |
| 30 | + self$register("uniform", function(min, max) { |
| 31 | + function(size = 1L) runif(size, min = min, max = max) |
| 32 | + }) |
| 33 | + self$register("discrete", function(values, prob) { |
| 34 | + values <- unlist(values) |
| 35 | + prob <- unlist(prob) |
| 36 | + # Validation (as not using a pre-made distribution function) |
| 37 | + stopifnot(length(values) == length(prob)) |
| 38 | + stopifnot(all(prob >= 0)) |
| 39 | + if (round(abs(sum(prob) - 1), 2) > 0.01) { |
| 40 | + stop(sprintf( |
| 41 | + "'prob' must sum to 1 ± 0.01. Sum: %s", abs(sum(unlist(prob))) |
| 42 | + )) |
| 43 | + } |
| 44 | + # Sampling function |
| 45 | + function(size = 1L) sample( |
| 46 | + values, size = size, replace = TRUE, prob = prob |
| 47 | + ) |
| 48 | + }) |
| 49 | + self$register("normal", function(mean, sd) { |
| 50 | + function(size = 1L) rnorm(size, mean = mean, sd = sd) |
| 51 | + }) |
| 52 | + self$register("lognormal", function(meanlog, sdlog) { |
| 53 | + function(size = 1L) rlnorm(size, meanlog = meanlog, sdlog = sdlog) |
| 54 | + }) |
| 55 | + self$register("poisson", function(lambda) { |
| 56 | + function(size = 1L) rpois(size, lambda = lambda) |
| 57 | + }) |
| 58 | + self$register("binomial", function(size_param, prob) { |
| 59 | + function(size = 1L) rbinom(size, size = size_param, prob = prob) |
| 60 | + }) |
| 61 | + self$register("geometric", function(prob) { |
| 62 | + function(size = 1L) rgeom(size, prob = prob) |
| 63 | + }) |
| 64 | + self$register("beta", function(shape1, shape2) { |
| 65 | + function(size = 1L) rbeta(size, shape1 = shape1, shape2 = shape2) |
| 66 | + }) |
| 67 | + self$register("gamma", function(shape, rate) { |
| 68 | + function(size = 1L) rgamma(size, shape = shape, rate = rate) |
| 69 | + }) |
| 70 | + self$register("chisq", function(df) { |
| 71 | + function(size = 1L) rchisq(size, df = df) |
| 72 | + }) |
| 73 | + self$register("t", function(df) { |
| 74 | + function(size = 1L) rt(size, df = df) |
| 75 | + }) |
| 76 | + }, |
| 77 | + |
| 78 | + #' @description |
| 79 | + #' Register a distribution generator under a name. |
| 80 | + #' |
| 81 | + #' Typically, the generator should be a function that: |
| 82 | + #' 1. Accepts parameters for a distribution. |
| 83 | + #' 2. Returns another function - the *sampler* - which takes a `size` |
| 84 | + #' argument and produces that many random values from the specified |
| 85 | + #' distribution. |
| 86 | + #' |
| 87 | + #' By storing generators rather than fixed samplers, you can create as many |
| 88 | + #' different samplers as you want later, each with different parameters, |
| 89 | + #' while reusing the same generator code. |
| 90 | + #' |
| 91 | + #' @param name Distribution name (string) |
| 92 | + #' @param generator Function to create a sampler given its parameters. |
| 93 | + register = function(name, generator) { |
| 94 | + self$registry[[name]] <- generator |
| 95 | + }, |
| 96 | + |
| 97 | + #' @description |
| 98 | + #' Get a registered distribution generator by name. |
| 99 | + #' |
| 100 | + #' @param name Distribution name (string) |
| 101 | + #' @return Generator function for the distribution. |
| 102 | + get = function(name) { |
| 103 | + if (!(name %in% names(self$registry))) |
| 104 | + stop( |
| 105 | + sprintf( |
| 106 | + c("Distribution '%s' not found.\nAvailable distributions:\n\t%s\n", |
| 107 | + "Use register() to add new distributions."), |
| 108 | + name, paste(names(self$registry), collapse = ",\n\t") |
| 109 | + ), |
| 110 | + call. = FALSE) |
| 111 | + self$registry[[name]] |
| 112 | + }, |
| 113 | + |
| 114 | + #' @description |
| 115 | + #' Convert mean/sd to lognormal parameters, returning the corresponding |
| 116 | + #' \code{meanlog} and \code{sdlog} parameters used by R's \code{rlnorm()}. |
| 117 | + #' |
| 118 | + #' @param params Named list with two elements: mean and sd. |
| 119 | + #' @return A named list of the same structure, but with elements |
| 120 | + #' \code{meanlog} and \code{sdlog} for each patient type. |
| 121 | + transform_to_lnorm = function(params) { |
| 122 | + variance <- params$sd^2L |
| 123 | + sigma_sq <- log(variance / (params$mean^2L) + 1L) |
| 124 | + sdlog <- sqrt(sigma_sq) |
| 125 | + meanlog <- log(params$mean) - sigma_sq / 2L |
| 126 | + list(meanlog = meanlog, sdlog = sdlog) |
| 127 | + }, |
| 128 | + |
| 129 | + #' @description |
| 130 | + #' Create a parameterised sampler for a distribution. |
| 131 | + #' |
| 132 | + #' The returned function draws random samples of a specified size from |
| 133 | + #' the given distribution with fixed parameters. |
| 134 | + #' |
| 135 | + #' For "lognormal", if "meanlog" and "sdlog" are present in the parameters, |
| 136 | + #' they will be used as-is. If not, but "mean" and "sd" are provided, these |
| 137 | + #' will be transformed into "meanlog"/"sdlog" automatically. |
| 138 | + #' |
| 139 | + #' @param name Distribution name |
| 140 | + #' @param ... Parameters for the generator |
| 141 | + #' @return A function that draws samples when called. |
| 142 | + create = function(name, ...) { |
| 143 | + dots <- list(...) |
| 144 | + if (name == "lognormal") { |
| 145 | + if (!is.null(dots$meanlog) && !is.null(dots$sdlog)) { |
| 146 | + dots <- dots |
| 147 | + } else if (!is.null(dots$mean) && !is.null(dots$sd)) { |
| 148 | + transformed <- self$transform_to_lnorm(dots) |
| 149 | + dots <- c(transformed, dots[setdiff(names(dots), c("mean", "sd"))]) |
| 150 | + } else { |
| 151 | + stop("Please supply either 'meanlog' and 'sdlog', or 'mean' and 'sd' ", |
| 152 | + "for a lognormal distribution.") |
| 153 | + } |
| 154 | + } |
| 155 | + # Calls the `get()` method above which finds the distribution generator |
| 156 | + # function, then do.call() populates it with dots (a list of arguments). |
| 157 | + generator <- self$get(name) |
| 158 | + do.call(generator, dots) |
| 159 | + }, |
| 160 | + |
| 161 | + #' @description |
| 162 | + #' Batch-create samplers from a configuration list. |
| 163 | + #' |
| 164 | + #' The configuration should be a list of lists, each sublist specifying a |
| 165 | + #' `class_name` (distribution) and `params` (parameter list for that |
| 166 | + #' distribution). |
| 167 | + #' |
| 168 | + #' @param config Named or unnamed list. Each entry is a list with |
| 169 | + #' 'class_name' and 'params'. |
| 170 | + #' @return List of parameterised samplers (named if config is named). |
| 171 | + create_batch = function(config) { |
| 172 | + if (is.list(config)) { |
| 173 | + # Calls `create()` for each distribution specified in config |
| 174 | + lapply(config, function(cfg) { |
| 175 | + do.call(self$create, c(cfg$class_name, cfg$params)) |
| 176 | + }) |
| 177 | + } else { |
| 178 | + stop("config must be a list (named or unnamed)", call. = FALSE) |
| 179 | + } |
| 180 | + } |
| 181 | +) |
| 182 | +) |
0 commit comments