diff --git a/dev/LICENSE-text.html b/dev/LICENSE-text.html index 2927c04..e3851e3 100644 --- a/dev/LICENSE-text.html +++ b/dev/LICENSE-text.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/LICENSE.html b/dev/LICENSE.html index 418599b..48f3136 100644 --- a/dev/LICENSE.html +++ b/dev/LICENSE.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/articles/fitting-dists-with-fitdistr.html b/dev/articles/fitting-dists-with-fitdistr.html index df1a8e0..224dd30 100644 --- a/dev/articles/fitting-dists-with-fitdistr.html +++ b/dev/articles/fitting-dists-with-fitdistr.html @@ -30,7 +30,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 @@ -81,7 +81,7 @@ Sam Abbott - +Under construction diff --git a/dev/articles/fitting-dists-with-stan.html b/dev/articles/fitting-dists-with-stan.html index 96af2f7..5a62279 100644 --- a/dev/articles/fitting-dists-with-stan.html +++ b/dev/articles/fitting-dists-with-stan.html @@ -30,7 +30,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 @@ -81,8 +81,285 @@ Sam Abbott - - + + +1 Introduction + + + +1.1 What are we going to do in this Vignette + +In this vignette, we’ll demonstrate how to use primarycensoreddist in conjunction with Stan for Bayesian inference of epidemiological delay distributions. We’ll cover the following key points: + +Simulating censored delay distribution data +Fitting a naive model using cmdstan +Evaluating the naive model’s performance +Fitting an improved model using primarycensoreddist functionality +Comparing the primarycensoreddist model’s performance to the naive model + + + + +1.2 What might I need to know before starting + +This vignette builds on the concepts introduced in the Getting Started with primarycensoreddist vignette and assumes familiarity with using Stan tools as covered in the How to use primarycensoreddist with Stan vignette. + + + +1.3 Packages used in this vignette + +Alongside the primarycensoreddist package we will use the cmdstanr package for interfacing with cmdstan. We will also use the ggplot2 package for plotting and dplyr for data manipulation. + +library(primarycensoreddist) +library(cmdstanr) +library(ggplot2) +library(dplyr) + + + + +2 Simulating censored and truncated delay distribution data + +We’ll start by simulating some censored and truncated delay distribution data. We’ll use the rprimarycensoreddist function (actually we will use the rpcens alias for brevity). + +set.seed(123) # For reproducibility + +# Define the true distribution parameters +n <- 1000 +meanlog <- 1.5 +sdlog <- 0.75 + +# Generate varying pwindow, swindow, and obs_time lengths +pwindows <- sample(1, n, replace = TRUE) +swindows <- sample(1, n, replace = TRUE) +obs_times <- 10 + +# Function to generate a single sample +generate_sample <- function(pwindow, swindow, obs_time) { + rpcens( + 1, rlnorm, + meanlog = meanlog, sdlog = sdlog, + pwindow = pwindow, swindow = swindow, D = obs_time + ) +} + +# Generate samples +samples <- mapply(generate_sample, pwindows, swindows, obs_times) + +# Create initial data frame +delay_data <- data.frame( + pwindow = pwindows, + swindow = swindows, + obs_time = obs_times, + observed_delay = samples +) + +head(delay_data) +## pwindow swindow obs_time observed_delay +## 1 1 1 10 2 +## 2 1 1 10 1 +## 3 1 1 10 8 +## 4 1 1 10 6 +## 5 1 1 10 5 +## 6 1 1 10 4 + +# Aggregate to unique combinations and count occurrences +# Aggregate to unique combinations and count occurrences +delay_counts <- delay_data |> + summarise(n = n(), .by = c(pwindow, swindow, obs_time, observed_delay)) + +head(delay_counts) +## pwindow swindow obs_time observed_delay n +## 1 1 1 10 2 160 +## 2 1 1 10 1 96 +## 3 1 1 10 8 59 +## 4 1 1 10 6 113 +## 5 1 1 10 5 119 +## 6 1 1 10 4 150 + +# Compare the samples with and without secondary censoring to the true +# distribution +# Calculate empirical CDF +empirical_cdf <- ecdf(samples) + +# Create a sequence of x values for the theoretical CDF +x_seq <- seq(min(samples), max(samples), length.out = 100) + +# Calculate theoretical CDF +theoretical_cdf <- plnorm(x_seq, meanlog = meanlog, sdlog = sdlog) + +# Create a long format data frame for plotting +cdf_data <- data.frame( + x = rep(x_seq, 2), + probability = c(empirical_cdf(x_seq), theoretical_cdf), + type = rep(c("Observed", "Theoretical"), each = length(x_seq)), + stringsAsFactors = FALSE +) + +# Plot +ggplot(cdf_data, aes(x = x, y = probability, color = type)) + + geom_step(linewidth = 1) + + scale_color_manual( + values = c(Observed = "#4292C6", Theoretical = "#252525") + ) + + geom_vline( + aes(xintercept = mean(samples), color = "Observed"), + linetype = "dashed", linewidth = 1 + ) + + geom_vline( + aes(xintercept = exp(meanlog + sdlog^2 / 2), color = "Theoretical"), + linetype = "dashed", linewidth = 1 + ) + + labs( + title = "Comparison of Observed vs Theoretical CDF", + x = "Delay", + y = "Cumulative Probability", + color = "CDF Type" + ) + + theme_minimal() + + theme( + panel.grid.minor = element_blank(), + plot.title = element_text(hjust = 0.5), + legend.position = "bottom" + ) + +We’ve aggregated the data to unique combinations of pwindow, swindow, and obs_time and counted the number of occurrences of each observed_delay for each combination. This is the data we will use to fit our model. + + + +3 Fitting a naive model using cmdstan + +We’ll start by fitting a naive model using cmdstan. We’ll use the cmdstanr package to interface with cmdstan. We define the model in a string and then write it to a file as in the How to use primarycensoreddist with Stan vignette. + +writeLines( + "data { + int<lower=0> N; // number of observations + vector[N] y; // observed delays + vector[N] n; // number of occurrences for each delay + } + parameters { + real mu; + real<lower=0> sigma; + } + model { + // Priors + mu ~ normal(1, 1); + sigma ~ normal(0.5, 1); + + // Likelihood + target += n .* lognormal_lpdf(y | mu, sigma); + }", + con = file.path(tempdir(), "naive_lognormal.stan") +) +Now let’s compile the model + +naive_model <- cmdstan_model(file.path(tempdir(), "naive_lognormal.stan")) +and now let’s fit the compiled model. + +naive_fit <- naive_model$sample( + data = list( + # Add a small constant to avoid log(0) + y = delay_counts$observed_delay + 1e-6, + n = delay_counts$n, + N = nrow(delay_counts) + ), + chains = 4, + parallel_chains = 4, + show_messages = FALSE, + refresh = 0 +) +naive_fit +## Warning: NAs introduced by coercion +## variable mean median sd mad q5 q95 rhat ess_bulk +## lp__ -28480.45 -28480.10 1.00 0.74 -28482.40 -28479.50 1.00 1999 +## mu -0.10 -0.10 0.05 0.04 -0.18 -0.02 1.00 2691 +## sigma 4.61 4.61 0.03 0.03 4.56 4.67 1.00 3820 +## ess_tail +## NA +## 2310 +## 2869 +We see that the model has converged and the diagnostics look good. However, just from the model posterior summary we see that we might not be very happy with the fit. mu is smaller than the target 1.5 and sigma is larger than the target 0.75. + + + +4 Fitting an improved model using primarycensoreddist + +We’ll now fit an improved model using the primarycensoreddist package. The main improvement is that we will use the primary_censored_dist_lpdf function to fit the model. This is the Stan version of the pcens() function and accounts for the primary and secondary censoring windows as well as the truncation. We encode that our primary distribution is a lognormal distribution by passing 1 as the dist_id parameter and that our primary event distribution is uniform by passing 1 as the primary_dist_id parameter. See the Stan documentation for more details on the primary_censored_dist_lpdf function. + +writeLines( + " + functions { + #include primary_censored_dist.stan + #include expgrowth.stan + } + data { + int<lower=0> N; // number of observations + array[N] int<lower=0> y; // observed delays + array[N] int<lower=0> n; // number of occurrences for each delay + array[N] int<lower=0> pwindow; // primary censoring window + array[N] int<lower=0> swindow; // secondary censoring window + array[N] int<lower=0> D; // maximum delay + } + transformed data { + array[0] real primary_params; + } + parameters { + real mu; + real<lower=0> sigma; + } + model { + // Priors + mu ~ normal(1, 1); + sigma ~ normal(0.5, 0.5); + + // Likelihood + for (i in 1:N) { + target += n[i] * primary_censored_dist_lpmf( + y[i] | 1, {mu, sigma}, + pwindow[i], swindow[i], D[i], + 1, primary_params + ); + } + }", + con = file.path(tempdir(), "primarycensoreddist_lognormal.stan") +) +Now let’s compile the model + +primarycensoreddist_model <- cmdstan_model( + file.path(tempdir(), "primarycensoreddist_lognormal.stan"), + include_paths = pcd_stan_path() +) +Now let’s fit the compiled model. + +primarycensoreddist_fit <- primarycensoreddist_model$sample( + data = list( + y = delay_counts$observed_delay, + n = delay_counts$n, + pwindow = delay_counts$pwindow, + swindow = delay_counts$swindow, + D = delay_counts$obs_time, + N = nrow(delay_counts) + ), + chains = 4, + parallel_chains = 4, + init = list( # we use this to resolve initialisation issues + list(mu = 1.5, sigma = 0.6), + list(mu = 1.5, sigma = 0.4), + list(mu = 1.5, sigma = 0.3), + list(mu = 1.5, sigma = 0.55) + ), + refresh = 0, + show_messages = FALSE +) +primarycensoreddist_fit +## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail +## lp__ -2134.42 -2134.13 0.97 0.70 -2136.43 -2133.49 1.00 732 952 +## mu 1.53 1.53 0.05 0.05 1.46 1.61 1.01 620 686 +## sigma 0.77 0.77 0.04 0.04 0.71 0.83 1.00 633 641 +We see that the model has converged and the diagnostics look good. We also see that the posterior means are very near the true parameters and the 90% credible intervals include the true parameters. + + diff --git a/dev/articles/fitting-dists-with-stan_files/figure-html/sample-lognormal-1.png b/dev/articles/fitting-dists-with-stan_files/figure-html/sample-lognormal-1.png new file mode 100644 index 0000000..51de988 Binary files /dev/null and b/dev/articles/fitting-dists-with-stan_files/figure-html/sample-lognormal-1.png differ diff --git a/dev/articles/index.html b/dev/articles/index.html index ca0fb75..8a25756 100644 --- a/dev/articles/index.html +++ b/dev/articles/index.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/articles/primarycensoreddist.html b/dev/articles/primarycensoreddist.html index 00ef3c0..e7ba36a 100644 --- a/dev/articles/primarycensoreddist.html +++ b/dev/articles/primarycensoreddist.html @@ -30,7 +30,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/articles/using-stan-tools.html b/dev/articles/using-stan-tools.html index 8830396..5f792ae 100644 --- a/dev/articles/using-stan-tools.html +++ b/dev/articles/using-stan-tools.html @@ -30,7 +30,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 @@ -103,10 +103,13 @@ 1.2 What is Stan and why are we using it Stan is a probabilistic programming language for statistical inference. It provides a flexible and efficient platform for Bayesian modeling and is widely used in various fields of data science and statistics. In this vignette, we’ll use Stan in conjunction with primarycensoreddist to perform Bayesian inference on censored data. -For more information on Stan: -- Stan’s official website -- Stan documentation -- Stan forums for community support and discussions +For more information on Stan: + +Stan’s official website +Stan documentation + +Stan forums for community support and discussions + @@ -152,7 +155,7 @@ Stan functions are accessed using the pcd_load_stan_functions() function. This function takes the name of the function as an argument and returns the function as a string. It can additionally write the functions to a file and wrap them in a functions{} block. pcd_load_stan_functions("primary_censored_dist_lpmf") -## [1] "// Stan functions from primarycensoreddist version 0.1.0.1000\nreal primary_censored_dist_lpmf(int d, int dist_id, array[] real params,\n data real pwindow, real swindow, data real D,\n int primary_dist_id, array[] real primary_params) {\n\n real d_upper = d + swindow;\n if (d_upper > D) {\n reject(\"Upper truncation point is greater than D. It is \", d_upper,\n \" and D is \", D, \". Resolve this by increasing D to be greater or equal to d + swindow.\");\n }\n real log_cdf_upper = primary_censored_dist_lcdf(\n d_upper | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n real log_cdf_lower = primary_censored_dist_lcdf(\n d | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n return log_diff_exp(log_cdf_upper, log_cdf_lower);\n}" +## [1] "// Stan functions from primarycensoreddist version 0.2.0.1000\nreal primary_censored_dist_lpmf(int d, int dist_id, array[] real params,\n data real pwindow, real swindow, data real D,\n int primary_dist_id, array[] real primary_params) {\n\n real d_upper = d + swindow;\n if (d_upper > D) {\n reject(\"Upper truncation point is greater than D. It is \", d_upper,\n \" and D is \", D, \". Resolve this by increasing D to be greater or equal to d + swindow.\");\n }\n real log_cdf_upper = primary_censored_dist_lcdf(\n d_upper | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n real log_cdf_lower = primary_censored_dist_lcdf(\n d | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n return log_diff_exp(log_cdf_upper, log_cdf_lower);\n}" @@ -171,13 +174,13 @@ output_file = expgrowth_rng_file, wrap_in_block = TRUE ) -## Stan functions written to: /tmp/RtmpaPRJO3/expgrowth_rng.stan +## Stan functions written to: /tmp/RtmpaPzbyH/expgrowth_rng.stan This can now be compiled and used in the same way as any other cmdstanr model. model <- cmdstan_model(expgrowth_rng_file) model ## functions { -## // Stan functions from primarycensoreddist version 0.1.0.1000 +## // Stan functions from primarycensoreddist version 0.2.0.1000 ## real expgrowth_rng(real min, real max, real r) { ## real u = uniform_rng(0, 1); ## if (abs(r) < 1e-10) { @@ -203,20 +206,44 @@ text = c( "functions {", "#include expgrowth.stan", + "}", + "generated quantities {", + " real y = expgrowth_rng(0, 1, 0.4);", "}" ), con = expgrowth_stan_file ) -} -We can now use this file to compile a model. **Note** that we need to include the path to the `primarycensoreddist` Stan functions using the `include_paths` argument to `cmdstan_model()`. - - -``` r -model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) -model +We can now use this file to compile a model. Note that we need to include the path to the primarycensoreddist Stan functions using the include_paths argument to cmdstan_model(). + +model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) +model ## functions { ## #include expgrowth.stan +## } +## generated quantities { +## real y = expgrowth_rng(0, 1, 0.4); ## } +We can then sample from the model (we set fixed_param = TRUE here as our toy example doesn’t require MCMC sampling). + +samples <- model$sample(chains = 1, fixed_param = TRUE) +## Running MCMC with 1 chain... +## +## Chain 1 Iteration: 1 / 1000 [ 0%] (Sampling) +## Chain 1 Iteration: 100 / 1000 [ 10%] (Sampling) +## Chain 1 Iteration: 200 / 1000 [ 20%] (Sampling) +## Chain 1 Iteration: 300 / 1000 [ 30%] (Sampling) +## Chain 1 Iteration: 400 / 1000 [ 40%] (Sampling) +## Chain 1 Iteration: 500 / 1000 [ 50%] (Sampling) +## Chain 1 Iteration: 600 / 1000 [ 60%] (Sampling) +## Chain 1 Iteration: 700 / 1000 [ 70%] (Sampling) +## Chain 1 Iteration: 800 / 1000 [ 80%] (Sampling) +## Chain 1 Iteration: 900 / 1000 [ 90%] (Sampling) +## Chain 1 Iteration: 1000 / 1000 [100%] (Sampling) +## Chain 1 finished in 0.0 seconds. + +samples +## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail +## y 0.51 0.52 0.29 0.38 0.06 0.95 1.00 1065 983 @@ -224,17 +251,12 @@ 2.4 Using Stan functions directly in R Whilst it is possible to use Stan functions directly in R it is not recommended for most use cases (use the R functions in primarycensoreddist instead). However, it can be useful to understand what is going on under the hood or for exploration (indeed we use this internally in primarycensoreddist to check our functions against the R implementations). To do this we use the expose_functions() method on our already compiled model. - + model$expose_functions(global = TRUE) -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_nvecserial.a -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_cvodes.a -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_idas.a -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_kinsol.a -## /home/runner/.cmdstan/cmdstan-2.35.0/stan/lib/stan_math/lib/tbb_2020.3/build/Makefile.tbb:28: CONFIG: cfg=release arch=intel64 compiler=gcc target=linux runtime=cc11.4.0_libc2.35_kernel6.5.0 We can now use the function in R. Note that this may get slightly more complicated if our stan function depends on other stan functions (i.e. you need to have those included in your compiled model as well). - + expgrowth_rng(0, 1, 0.4) -## [1] 0.5643954 +## [1] 0.6524848 -primarycensoreddist 0.1.0.1000 +primarycensoreddist 0.2.0.1000 +Development version. + + +primarycensoreddist 0.2.0 +This release puts in place initial documentation and vignettes. It also includes a new primary censored distribution interface to allow for non-secondary event censored distributions. Development of this release as identified some numerical issues in the gradient evaluations for the primary censored distributions which may lead to breaking interface changes in 0.3.0 for the Stan code. -Package +Package Added support for swindow = 0 to rprimarycensoreddist to allow for non-secondary event censored distributions. Adapted rprimarycensoreddist so that truncation is based on the primary censored distribution before secondary events are censored. This better matches the generative process. Added a new Stan interface tool to enable finding which files functions are implemented in the Stan code. -Documentation +Documentation Added a getting started vignette. Added a vignette showcasing how to use the package Stan code with cmdstanr. +Added a vignette showcasing how to fit distributions using the cmdstanr package. diff --git a/dev/pkgdown.yml b/dev/pkgdown.yml index 5849705..d5a2911 100644 --- a/dev/pkgdown.yml +++ b/dev/pkgdown.yml @@ -6,7 +6,7 @@ articles: fitting-dists-with-stan: fitting-dists-with-stan.html primarycensoreddist: primarycensoreddist.html using-stan-tools: using-stan-tools.html -last_built: 2024-09-04T20:35Z +last_built: 2024-09-04T21:41Z urls: reference: https://primarycensoreddist.epinowcast.org/reference article: https://primarycensoreddist.epinowcast.org/articles diff --git a/dev/reference/check_dprimary.html b/dev/reference/check_dprimary.html index 3b9fc74..74798ea 100644 --- a/dev/reference/check_dprimary.html +++ b/dev/reference/check_dprimary.html @@ -11,7 +11,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/check_pdist.html b/dev/reference/check_pdist.html index ea8b31b..b6a83d5 100644 --- a/dev/reference/check_pdist.html +++ b/dev/reference/check_pdist.html @@ -9,7 +9,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/dot-extract_stan_functions.html b/dev/reference/dot-extract_stan_functions.html index b7fb520..64bfec1 100644 --- a/dev/reference/dot-extract_stan_functions.html +++ b/dev/reference/dot-extract_stan_functions.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/dprimarycensoreddist.html b/dev/reference/dprimarycensoreddist.html index 508df5c..a738d97 100644 --- a/dev/reference/dprimarycensoreddist.html +++ b/dev/reference/dprimarycensoreddist.html @@ -15,7 +15,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/expgrowth.html b/dev/reference/expgrowth.html index 39916de..5bfa0a5 100644 --- a/dev/reference/expgrowth.html +++ b/dev/reference/expgrowth.html @@ -9,7 +9,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/index.html b/dev/reference/index.html index b091cb7..5735c50 100644 --- a/dev/reference/index.html +++ b/dev/reference/index.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/pcd_load_stan_functions.html b/dev/reference/pcd_load_stan_functions.html index 5294fe4..2346b0c 100644 --- a/dev/reference/pcd_load_stan_functions.html +++ b/dev/reference/pcd_load_stan_functions.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/pcd_stan_files.html b/dev/reference/pcd_stan_files.html index 7566cf6..c80eae8 100644 --- a/dev/reference/pcd_stan_files.html +++ b/dev/reference/pcd_stan_files.html @@ -9,7 +9,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/pcd_stan_functions.html b/dev/reference/pcd_stan_functions.html index c4702fc..8e5c04d 100644 --- a/dev/reference/pcd_stan_functions.html +++ b/dev/reference/pcd_stan_functions.html @@ -9,7 +9,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/pcd_stan_path.html b/dev/reference/pcd_stan_path.html index 5ed0def..e3d0220 100644 --- a/dev/reference/pcd_stan_path.html +++ b/dev/reference/pcd_stan_path.html @@ -7,7 +7,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/pprimarycensoreddist.html b/dev/reference/pprimarycensoreddist.html index 9fe4de2..cf57a3e 100644 --- a/dev/reference/pprimarycensoreddist.html +++ b/dev/reference/pprimarycensoreddist.html @@ -15,7 +15,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/reference/rprimarycensoreddist.html b/dev/reference/rprimarycensoreddist.html index d3b2491..b4a3b18 100644 --- a/dev/reference/rprimarycensoreddist.html +++ b/dev/reference/rprimarycensoreddist.html @@ -15,7 +15,7 @@ primarycensoreddist - 0.1.0.1000 + 0.2.0.1000 diff --git a/dev/search.json b/dev/search.json index 6dc1d50..9125976 100644 --- a/dev/search.json +++ b/dev/search.json @@ -1 +1 @@ -[{"path":"https://primarycensoreddist.epinowcast.org/dev/LICENSE.html","id":null,"dir":"","previous_headings":"","what":"MIT License","title":"MIT License","text":"Copyright (c) 2024 primarycensoreddist authors Permission hereby granted, free charge, person obtaining copy software associated documentation files (“Software”), deal Software without restriction, including without limitation rights use, copy, modify, merge, publish, distribute, sublicense, /sell copies Software, permit persons Software furnished , subject following conditions: copyright notice permission notice shall included copies substantial portions Software. SOFTWARE PROVIDED “”, WITHOUT WARRANTY KIND, EXPRESS IMPLIED, INCLUDING LIMITED WARRANTIES MERCHANTABILITY, FITNESS PARTICULAR PURPOSE NONINFRINGEMENT. EVENT SHALL AUTHORS COPYRIGHT HOLDERS LIABLE CLAIM, DAMAGES LIABILITY, WHETHER ACTION CONTRACT, TORT OTHERWISE, ARISING , CONNECTION SOFTWARE USE DEALINGS SOFTWARE.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"introduction","dir":"Articles","previous_headings":"","what":"Introduction","title":"Getting Started with primarycensoreddist","text":"Delay distributions play crucial role various fields, including epidemiology, reliability analysis, survival analysis. distributions describe time two events interest, incubation period disease time failure component. Accurately estimating calculating distributions essential understanding underlying processes making informed decisions[1]. However, estimating distributions can challenging due various factors, including censoring truncation observed data[2]. estimation delay distributions often faces following challenges: Primary event censoring: primary event (e.g., exposure pathogen start process) often observed degree interval censoring. means exact time event known, rather, known occurred within certain time interval, commonly day. result, distribution based primary events combination underlying true distribution censoring distribution. Truncation: observation delay distributions often conditioned occurrence secondary event. leads truncation observed distribution, delays longer observation time captured data. Consequently, observed distribution combination underlying true distribution, censoring distribution, observation time. Secondary event censoring: secondary event (e.g., symptom onset end process) also frequently observed interval censoring. additional layer censoring complicates estimation delay distribution. primarycensoreddist package aims address challenges providing tools manipulate primary censored delay distributions. accounting censoring truncation present data, package enables accurate estimation use underlying true distribution. vignette, provide quick introduction main functions concepts primarycensoreddist package. cover mathematical formulation problem, demonstrate usage key functions, provide signposting learn .","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"packages-in-this-getting-started-vignette-","dir":"Articles","previous_headings":"","what":"Packages in this getting started vignette.","title":"Getting Started with primarycensoreddist","text":"well primarycensoreddist package vignette also uses ggplot2.","code":"# Load packages library(primarycensoreddist) library(ggplot2) # Set seed for reproducibility set.seed(123)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"generating-random-samples-with-rprimarycensoreddist","dir":"Articles","previous_headings":"","what":"Generating Random Samples with rprimarycensoreddist()","title":"Getting Started with primarycensoreddist","text":"function generates random samples primary event censored distribution. adjusts distribution accounting primary event distribution, potential truncation maximum delay (D), secondary event censoring. mathematical formulation generating random samples primary event censored distribution follows: Generate primary event times (\\(p\\)) specified primary event distribution (\\(f_p\\)) within primary event window (\\(pwindow\\)): \\[p \\sim f_p(x), \\quad 0 \\leq x \\leq pwindow\\] Generate delays (\\(d\\)) specified delay distribution (\\(f_d\\)) parameters \\(\\theta\\): \\[d \\sim f_d(x; \\theta)\\] Calculate total delays (\\(t\\)) adding primary event times delays: \\[t = p + d\\] Apply truncation ensure delays within specified range \\([0, D]\\): \\[t_{truncated} = \\{t \\mid 0 \\leq t < D\\}\\] Round truncated delays nearest secondary event window (\\(swindow\\)): \\[t_{valid} = \\lfloor \\frac{t_{truncated}}{swindow} \\rfloor \\times swindow\\] ’s example use rprimarycensoreddist() sample log-normal distribution without secondary interval censoring. simplicity use daily secondary censoring window events. Neither distribution matches true distribution due truncation D biases observed distributions towards shorter delays primary secondary event censoring.","code":"n <- 1e4 meanlog <- 1.5 sdlog <- 0.75 obs_time <- 10 pwindow <- 1 # Random samples without secondary censoring samples <- rprimarycensoreddist( n, rlnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = 0, D = obs_time ) # Random samples with secondary censoring samples_sc <- rprimarycensoreddist( n, rlnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = 1, D = obs_time ) # Calculate the PMF for the samples with secondary censoring samples_sc_pmf <- data.frame( pmf = table(samples_sc) / sum(table(samples_sc)) ) # Compare the samples with and without secondary censoring to the true # distribution ggplot() + geom_density( data = data.frame(samples = samples), aes(x = samples), fill = \"#4292C6\", col = \"#252525\", alpha = 0.5 ) + geom_col( data = samples_sc_pmf, aes( x = as.numeric(as.character(pmf.samples_sc)), y = pmf.Freq ), fill = \"#20b986\", col = \"#252525\", alpha = 0.5, width = 0.9, just = 0 ) + geom_function( fun = dlnorm, args = list(meanlog = meanlog, sdlog = sdlog), color = \"#252525\", linewidth = 1 ) + labs( title = \"Comparison of Samples from Log-Normal Distribution\", x = \"Samples\", y = \"Density\", caption = paste0( \"Blue density: Samples without secondary censoring\\n\", \"Green bars: Samples with secondary censoring\\n\", \"Black line: True log-normal distribution without truncation\" ) ) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5) )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"compute-the-primary-event-censored-cumulative-distribution-function-cdf-for-delays-with-pprimarycensoreddist","dir":"Articles","previous_headings":"","what":"Compute the primary event censored cumulative distribution function (CDF) for delays with pprimarycensoreddist()","title":"Getting Started with primarycensoreddist","text":"function computes primary event censored cumulative distribution function (CDF) given set quantiles. adjusts CDF delay distribution accounting primary event distribution potential truncation maximum delay (D). primary event censored CDF, (\\(F_{\\text{cens}}(q)\\)), given : \\[ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} F(q - p) \\cdot f_{\\text{primary}}(p) \\, dp \\] (\\(F\\)) CDF primary event distribution, (\\(f_{\\text{primary}}\\)) PDF primary event times, (\\(pwindow\\)) primary event window. maximum delay (\\(D\\)) finite, CDF normalized (\\(F(D)\\)): \\[ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} \\frac{F(q - p)}{F(D - p)} \\cdot f_{\\text{primary}}(p) \\, dp \\] Let’s compare empirical CDF samples without secondary censoring theoretical CDF computed using pprimarycensoreddist(): theoretical CDF matches empirical CDF well, confirming pprimarycensoreddist() working expected.","code":"empirical_cdf <- ecdf(samples) theoretical_cdf <- pprimarycensoreddist( seq(0, obs_time, length.out = 100), plnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, D = obs_time ) # Create a data frame for plotting cdf_data <- data.frame( x = seq(0, obs_time, length.out = 100), Theoretical = theoretical_cdf, Empirical = empirical_cdf(seq(0, obs_time, length.out = 100)) ) # Plot the empirical and theoretical CDFs ggplot(cdf_data, aes(x = x)) + geom_step(aes(y = Theoretical), color = \"black\", linewidth = 1) + geom_step(aes(y = Empirical), color = \"#4292C6\", linewidth = 1) + labs( title = \"Comparison of Empirical and Theoretical CDFs\", x = \"Delay\", y = \"Cumulative Probability\", caption = paste0( \"Blue line: Empirical CDF from samples without secondary censoring\\n\", \"Black line: Theoretical CDF computed using pprimarycensoreddist()\" ) ) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5) )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"compute-the-primary-event-censored-probability-mass-function-pmfwith-dprimarycensoreddist","dir":"Articles","previous_headings":"","what":"Compute the primary event censored probability mass function (PMF)with dprimarycensoreddist()","title":"Getting Started with primarycensoreddist","text":"function computes primary event censored probability mass function (PMF) given set quantiles using CDF. top accounting primary event distribution truncation also accounts secondary event censoring. primary event censored PMF, (\\(f_{\\text{cens}}(d)\\)), given : \\[ f_{\\text{cens}}(d) = F_{\\text{cens}}(d + \\text{swindow}) - F_{\\text{cens}}(d) \\] (\\(F_{\\text{cens}}\\)) potentially right truncated primary event censored CDF (\\(\\text{swindow}\\)) secondary event window. Let’s compare empirical PMF samples secondary censoring theoretical PMF computed using dprimarycensoreddist(): theoretical PMF matches empirical PMF well, confirming dprimarycensoreddist() also working expected.","code":"# Calculate the theoretical PMF using dprimarycensoreddist theoretical_pmf <- dprimarycensoreddist( 0:(obs_time - 1), plnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = 1, D = obs_time ) pmf_df <- data.frame( x = 0:obs_time, pmf = c(theoretical_pmf, 0) ) # Plot the empirical and theoretical PMFs ggplot() + geom_col( data = samples_sc_pmf, aes( x = as.numeric(as.character(pmf.samples_sc)), y = pmf.Freq ), fill = \"#20b986\", col = \"#252525\", alpha = 0.5, width = 0.9, just = 0 ) + geom_step( data = pmf_df, aes(x = x, y = pmf), color = \"black\", linewidth = 1 ) + labs( title = \"Comparison of Samples from Log-Normal Distribution\", x = \"Samples\", y = \"Density\", caption = paste0( \"Green bars: Empirical PMF from samples with secondary censoring\\n\", \"Black line: Theoretical PMF computed using dprimarycensoreddist()\" ) ) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5) )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"other-key-functionality","dir":"Articles","previous_headings":"","what":"Other key functionality","title":"Getting Started with primarycensoreddist","text":"addition main functions, package also includes: Primary event distributions: package includes commonly used primary event distributions exponential growth. Stan versions functions R functions interface Stan: R functions corresponding Stan function. Stan functions used estimation delay distributions using Stan software. package also includes tools manipulate Stan code R.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"learning-more","dir":"Articles","previous_headings":"","what":"Learning more","title":"Getting Started with primarycensoreddist","text":"primarycensoreddist see package vignettes function documentation. methodological background delay distributions see Park et al.[2]. advice best practices estimating handling delay distributions see Charniga et al.[1].","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"what-are-we-going-to-do-in-this-vignette","dir":"Articles","previous_headings":"1 Introduction","what":"What are we going to do in this Vignette","title":"How to use primarycensoreddist with Stan","text":"vignette, ’ll explore use primarycensoreddist package conjunction Stan. ’ll cover following key points: Introduction Stan relevance analysis Overview packages ’ll using access use Stan functions provided primarycensoreddist Methods integrating Stan functions workflow","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"what-is-stan-and-why-are-we-using-it","dir":"Articles","previous_headings":"1 Introduction","what":"What is Stan and why are we using it","title":"How to use primarycensoreddist with Stan","text":"Stan probabilistic programming language statistical inference. provides flexible efficient platform Bayesian modeling widely used various fields data science statistics. vignette, ’ll use Stan conjunction primarycensoreddist perform Bayesian inference censored data. information Stan: - Stan’s official website - Stan documentation - Stan forums community support discussions","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"packages-used-in-this-vignette","dir":"Articles","previous_headings":"1 Introduction","what":"Packages used in this vignette","title":"How to use primarycensoreddist with Stan","text":"Alongside primarycensoreddist package use cmdstanr package interfacing cmdstan.","code":"library(primarycensoreddist) library(cmdstanr)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"using-stan-code-in-primarycensoreddist","dir":"Articles","previous_headings":"","what":"Using Stan code in primarycensoreddist","title":"How to use primarycensoreddist with Stan","text":"primarycensoreddist includes set Stan functions mirror R functions primarycensoreddist. Documentation functions can found . support range approaches integrate Stan code workflow.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"checking-available-stan-functions-using-pcd_stan_functions","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist","what":"Checking available Stan functions using pcd_stan_functions()","title":"How to use primarycensoreddist with Stan","text":"Aside reading documentation also possible list available Stan functions using helper function directly R.","code":"pcd_stan_functions() ## [1] \"expgrowth_pdf\" ## [2] \"expgrowth_lpdf\" ## [3] \"expgrowth_cdf\" ## [4] \"expgrowth_lcdf\" ## [5] \"expgrowth_rng\" ## [6] \"dist_lcdf\" ## [7] \"primary_dist_lpdf\" ## [8] \"primary_censored_integrand\" ## [9] \"primary_censored_dist_cdf\" ## [10] \"primary_censored_dist_lcdf\" ## [11] \"primary_censored_dist_lpmf\" ## [12] \"primary_censored_dist_pmf\" ## [13] \"primary_censored_sone_lpmf_vectorized\" ## [14] \"primary_censored_sone_pmf_vectorized\""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"accessing-stan-functions","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist","what":"Accessing Stan functions","title":"How to use primarycensoreddist with Stan","text":"Stan functions accessed using pcd_load_stan_functions() function. function takes name function argument returns function string. can additionally write functions file wrap functions{} block.","code":"pcd_load_stan_functions(\"primary_censored_dist_lpmf\") ## [1] \"// Stan functions from primarycensoreddist version 0.1.0.1000\\nreal primary_censored_dist_lpmf(int d, int dist_id, array[] real params,\\n data real pwindow, real swindow, data real D,\\n int primary_dist_id, array[] real primary_params) {\\n\\n real d_upper = d + swindow;\\n if (d_upper > D) {\\n reject(\\\"Upper truncation point is greater than D. It is \\\", d_upper,\\n \\\" and D is \\\", D, \\\". Resolve this by increasing D to be greater or equal to d + swindow.\\\");\\n }\\n real log_cdf_upper = primary_censored_dist_lcdf(\\n d_upper | dist_id, params, pwindow, D, primary_dist_id, primary_params\\n );\\n real log_cdf_lower = primary_censored_dist_lcdf(\\n d | dist_id, params, pwindow, D, primary_dist_id, primary_params\\n );\\n return log_diff_exp(log_cdf_upper, log_cdf_lower);\\n}\""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"writing-functions-to-a-file","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist > 2.3 Linking the Stan functions to your workflow","what":"Writing functions to a file","title":"How to use primarycensoreddist with Stan","text":"One option using Stan functions write file compile using cmdstanr. good approach means functions written can used way stan functions might use. downside may mean work keeping date changes functions. can using pcd_load_stan_functions() function. can now compiled used way cmdstanr model. Alternatively, use #include expgrowth_rng.stan stan file functions block include function along path file stan file (see ).","code":"expgrowth_rng_file <- file.path(tempdir(), \"expgrowth_rng.stan\") exp_model <- pcd_load_stan_functions( \"expgrowth_rng\", write_to_file = TRUE, output_file = expgrowth_rng_file, wrap_in_block = TRUE ) ## Stan functions written to: /tmp/RtmpaPRJO3/expgrowth_rng.stan model <- cmdstan_model(expgrowth_rng_file) model ## functions { ## // Stan functions from primarycensoreddist version 0.1.0.1000 ## real expgrowth_rng(real min, real max, real r) { ## real u = uniform_rng(0, 1); ## if (abs(r) < 1e-10) { ## return min + u * (max - min); ## } ## return min + log(u * (exp(r * max) - exp(r * min)) + exp(r * min)) / r; ## } ## }"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"including-the-functions-directly-via-include_paths","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist > 2.3 Linking the Stan functions to your workflow","what":"Including the functions directly via include_paths","title":"How to use primarycensoreddist with Stan","text":"Rather writing functions file also possible include directly stan file using include_paths argument cmdstan_model(). useful don’t clutter model stan code primarycensoreddist want automatic updating functions. demonstrate first write small model expgrowth.stan include paths (rather writing file including ). first step find file path expgrowth_rng function. done now write stan wrapper model. }","code":"pcd_stan_files(\"expgrowth_rng\") ## [1] \"expgrowth.stan\" expgrowth_stan_file <- file.path(tempdir(), \"expgrowth.stan\") writeLines( text = c( \"functions {\", \"#include expgrowth.stan\", \"}\" ), con = expgrowth_stan_file ) We can now use this file to compile a model. **Note** that we need to include the path to the `primarycensoreddist` Stan functions using the `include_paths` argument to `cmdstan_model()`. ``` r model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) model ## functions { ## #include expgrowth.stan ## }"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"using-stan-functions-directly-in-r","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist","what":"Using Stan functions directly in R","title":"How to use primarycensoreddist with Stan","text":"Whilst possible use Stan functions directly R recommended use cases (use R functions primarycensoreddist instead). However, can useful understand going hood exploration (indeed use internally primarycensoreddist check functions R implementations). use expose_functions() method already compiled model. can now use function R. Note may get slightly complicated stan function depends stan functions (.e. need included compiled model well).","code":"model$expose_functions(global = TRUE) ## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_nvecserial.a ## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_cvodes.a ## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_idas.a ## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_kinsol.a ## /home/runner/.cmdstan/cmdstan-2.35.0/stan/lib/stan_math/lib/tbb_2020.3/build/Makefile.tbb:28: CONFIG: cfg=release arch=intel64 compiler=gcc target=linux runtime=cc11.4.0_libc2.35_kernel6.5.0 expgrowth_rng(0, 1, 0.4) ## [1] 0.5643954"},{"path":"https://primarycensoreddist.epinowcast.org/dev/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Sam Abbott. Author, maintainer.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Sam Abbott (2024). primarycensoreddist: Primary Event Censored Distributions R Stan. doi:10.5281/zenodo.13632839.","code":"@Manual{, title = {primarycensoreddist: Primary Event Censored Distributions in R and Stan}, author = {{Sam Abbott}}, year = {2024}, doi = {10.5281/zenodo.13632839}, }"},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"summary","dir":"","previous_headings":"","what":"Summary","title":"Primary Event Censored Distributions in R and Stan","text":"package provides R functions working primary event censored distributions Stan implementations use Bayesian modeling. Primary event censored distributions useful modeling delayed reporting scenarios epidemiology fields. provides support arbitrary delay distributions, range common primary distributions, allows truncation secondary event censoring accounted .","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Primary Event Censored Distributions in R and Stan","text":"can install latest released version using normal R function, though need point r-universe instead CRAN: Alternatively, can use remotes package install development version Github (warning! version may contain breaking changes /bugs): Similarly, can install historical versions specifying release tag (e.g. installs 0.2.0): Note: can also use last approach install specific commit needed, e.g. want try specific unreleased feature, absolute latest developmental version. wish use Stan functions, need install CmdStan, also entails suitable C++ toolchain setup. recommend using cmdstanr package. Stan team provides instructions Getting started cmdstanr vignette, details support package site along key instructions available Stan resources package vignette, brief version : Note: can speed CmdStan installation using cores argument. installing particular version epinowcast, may also need install past version CmdStan, can version argument.","code":"install.packages( \"primarycensoreddist\", repos = \"https://epinowcast.r-universe.dev\" ) remotes::install_github( \"epinowcast/primarycensoreddist\", dependencies = TRUE ) remotes::install_github( \"epinowcast/primarycensoreddist\", dependencies = TRUE, ref = \"v0.2.0\" ) # if you not yet installed `primarycensoreddist`, or you installed it without # `Suggests` dependencies install.packages( \"cmdstanr\", repos = c(\"https://stan-dev.r-universe.dev\", getOption(\"repos\")) ) # once `cmdstanr` is installed: cmdstanr::install_cmdstan()"},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"resources","dir":"","previous_headings":"","what":"Resources","title":"Primary Event Censored Distributions in R and Stan","text":"provide range documentation, case studies, community spaces ask (answer!) questions: primarycensoreddist website includes function reference, model outline, case studies using package. site mainly concerns release version, can also find documentation latest development version. created package vignettes help get started primarycensoreddist highlight features case studies. organisation website includes links resources, guest posts, seminar schedule upcoming past recordings. community forum areas question answer considering new methods tools, among others. generally interested real-time analysis infectious disease, may find useful even use primarycensoreddist.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"contributing","dir":"","previous_headings":"","what":"Contributing","title":"Primary Event Censored Distributions in R and Stan","text":"welcome contributions new contributors! particularly appreciate help identifying identified issues. Please check add issues, /add pull request see contributing guide information. need different underlying model work: primarycensoreddist provides flexible framework censored distributions R Stan. implement new distributions censoring mechanisms expand overall flexibility improve defaults, please let us know either community forum. always like hear new use-cases extensions package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"how-to-make-a-bug-report-or-feature-request","dir":"","previous_headings":"Contributing","what":"How to make a bug report or feature request","title":"Primary Event Censored Distributions in R and Stan","text":"Please briefly describe problem output expect issue. question, please don’t open issue. Instead, ask Q page. See contributing guide information.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"code-of-conduct","dir":"","previous_headings":"Contributing","what":"Code of Conduct","title":"Primary Event Censored Distributions in R and Stan","text":"Please note primarycensoreddist project released Contributor Code Conduct. contributing project, agree abide terms.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Primary Event Censored Distributions in R and Stan","text":"making use methodology methodology based, please cite relevant papers methods outline. use primarycensoreddist work, please consider citing citation(\"primarycensoreddist\").","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"contributors","dir":"","previous_headings":"","what":"Contributors","title":"Primary Event Censored Distributions in R and Stan","text":"contributions project gratefully acknowledged using allcontributors package following -contributors specification. Contributions kind welcome!","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"code","dir":"","previous_headings":"Contributors","what":"Code","title":"Primary Event Censored Distributions in R and Stan","text":"seabbs","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"issue-authors","dir":"","previous_headings":"Contributors","what":"Issue Authors","title":"Primary Event Censored Distributions in R and Stan","text":"zsusswein, SamuelBrand1","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"issue-contributors","dir":"","previous_headings":"Contributors","what":"Issue Contributors","title":"Primary Event Censored Distributions in R and Stan","text":"athowes","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":null,"dir":"Reference","previous_headings":"","what":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"function tests whether given function behaves like valid PDF checking integrates approximately 1 specified range takes arguments min max.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"","code":"check_dprimary(dprimary, pwindow, dprimary_args = list(), tolerance = 0.001)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"dprimary Function generate probability density function (PDF) primary event times. function take value x pwindow parameter, return probability density. normalized integrate 1 [0, pwindow]. Defaults uniform distribution [0, pwindow]. Users can provide custom functions use helper functions like dexpgrowth exponential growth distribution. See primary_dists.R examples. pwindow Primary event window dprimary_args List additional arguments passed dprimary. example, using dexpgrowth, pass list(min = 0, max = pwindow, r = 0.2) set minimum, maximum, rate parameters. tolerance tolerance integral considered close 1","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"NULL. function stop execution error message dprimary valid PDF.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"","code":"check_dprimary(dunif, pwindow = 1)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":null,"dir":"Reference","previous_headings":"","what":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"function tests whether given function behaves like valid CDF checking monotonically increasing bounded 0 1.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"","code":"check_pdist(pdist, D, ...)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"pdist Distribution function (CDF) D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. ... Additional arguments passed pdist","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"NULL. function stop execution error message pdist valid CDF.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"","code":"check_pdist(pnorm, D = 10)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract function names or content from Stan code — .extract_stan_functions","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"Extract function names content Stan code","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"","code":".extract_stan_functions(content, names_only = FALSE, functions = NULL)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"content Character vector containing Stan code names_only Logical, TRUE extract function names, otherwise extract function content. functions Optional, character vector function names extract content .","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"Character vector function names content","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute the primary event censored PMF for delays — dprimarycensoreddist","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"function computes primary event censored probability mass function (PMF) given set quantiles. adjusts PMF primary event distribution accounting delay distribution potential truncation maximum delay (D). function allows custom primary event distributions delay distributions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"","code":"dprimarycensoreddist( x, pdist, pwindow = 1, swindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), log = FALSE, ... ) dpcens( x, pdist, pwindow = 1, swindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), log = FALSE, ... )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"x Vector quantiles pdist Distribution function (CDF) pwindow Primary event window swindow Secondary event window (default: 1) D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. dprimary Function generate probability density function (PDF) primary event times. function take value x pwindow parameter, return probability density. normalized integrate 1 [0, pwindow]. Defaults uniform distribution [0, pwindow]. Users can provide custom functions use helper functions like dexpgrowth exponential growth distribution. See primary_dists.R examples. dprimary_args List additional arguments passed dprimary. example, using dexpgrowth, pass list(min = 0, max = pwindow, r = 0.2) set minimum, maximum, rate parameters. log Logical; TRUE, probabilities p given log(p) ... Additional arguments passed distribution function","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"Vector primary event censored PMFs, normalized D finite (truncation adjustment)","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"primary event censored PMF computed taking difference primary event censored cumulative distribution function (CDF) two points, \\(d + \\text{swindow}\\) \\(d\\). primary event censored PMF, \\(f_{\\text{cens}}(d)\\), given : $$ f_{\\text{cens}}(d) = F_{\\text{cens}}(d + \\text{swindow}) - F_{\\text{cens}}(d) $$ \\(F_{\\text{cens}}\\) primary event censored CDF. explanation mathematical details CDF, refer documentation pprimarycensoreddist().","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"","code":"# Example: Weibull distribution with uniform primary events dprimarycensoreddist(c(0.1, 0.5, 1), pweibull, shape = 1.5, scale = 2.0) #> [1] 0.1577952 0.2735269 0.3463199 # Example: Weibull distribution with exponential growth primary events dprimarycensoreddist( c(0.1, 0.5, 1), pweibull, dprimary = dexpgrowth, dprimary_args = list(r = 0.2), shape = 1.5, scale = 2.0 ) #> [1] 0.1522796 0.2691280 0.3459055"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":null,"dir":"Reference","previous_headings":"","what":"Exponential growth distribution functions — expgrowth","title":"Exponential growth distribution functions — expgrowth","text":"Density, distribution function, random generation exponential growth distribution.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Exponential growth distribution functions — expgrowth","text":"","code":"dexpgrowth(x, min = 0, max = 1, r, log = FALSE) pexpgrowth(q, min = 0, max = 1, r, lower.tail = TRUE, log.p = FALSE) rexpgrowth(n, min = 0, max = 1, r)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Exponential growth distribution functions — expgrowth","text":"x, q Vector quantiles. min Minimum value distribution range. Default 0. max Maximum value distribution range. Default 1. r Rate parameter exponential growth. log, log.p Logical; TRUE, probabilities p given log(p). lower.tail Logical; TRUE (default), probabilities P[X ≤ x], otherwise, P[X > x]. n Number observations. length(n) > 1, length taken number required.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Exponential growth distribution functions — expgrowth","text":"dexpgrowth gives density, pexpgrowth gives distribution function, rexpgrowth generates random deviates. length result determined n rexpgrowth, maximum lengths numerical arguments functions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Exponential growth distribution functions — expgrowth","text":"exponential growth distribution defined interval [min, max] rate parameter (r). probability density function (PDF) : $$f(x) = \\frac{r \\cdot \\exp(r \\cdot (x - min))}{\\exp(r \\cdot max) - \\exp(r \\cdot min)}$$ cumulative distribution function (CDF) : $$F(x) = \\frac{\\exp(r \\cdot (x - min)) - \\exp(r \\cdot min)}{ \\exp(r \\cdot max) - \\exp(r \\cdot min)}$$ random number generation, use inverse transform sampling method: Generate \\(u \\sim \\text{Uniform}(0,1)\\) Set \\(F(x) = u\\) solve \\(x\\): $$ x = min + \\frac{1}{r} \\cdot \\log(u \\cdot (\\exp(r \\cdot max) - \\exp(r \\cdot min)) + \\exp(r \\cdot min)) $$ method works probability integral transform theorem, states \\(X\\) continuous random variable CDF \\(F(x)\\), \\(Y = F(X)\\) follows \\(\\text{Uniform}(0,1)\\) distribution. Conversely, \\(U\\) \\(\\text{Uniform}(0,1)\\) random variable, \\(F^{-1}(U)\\) distribution \\(X\\), \\(F^{-1}\\) inverse CDF. case, generate \\(u\\) \\(\\text{Uniform}(0,1)\\), solve \\(F(x) = u\\) \\(x\\) get sample exponential growth distribution. formula \\(x\\) derived algebraically solving equation: $$ u = \\frac{\\exp(r \\cdot (x - min)) - \\exp(r \\cdot min)}{\\exp(r \\cdot max) - \\exp(r \\cdot min)} $$ \\(r\\) close 0 (\\(|r| < 1e-10\\)), distribution approximates uniform distribution [min, max], use simpler method generate samples directly uniform distribution.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Exponential growth distribution functions — expgrowth","text":"","code":"x <- seq(0, 1, by = 0.1) probs <- dexpgrowth(x, r = 0.2) cumprobs <- pexpgrowth(x, r = 0.2) samples <- rexpgrowth(100, r = 0.2)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Load Stan functions as a string — pcd_load_stan_functions","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"Load Stan functions string","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"","code":"pcd_load_stan_functions( functions = NULL, stan_path = primarycensoreddist::pcd_stan_path(), wrap_in_block = FALSE, write_to_file = FALSE, output_file = \"pcd_functions.stan\" )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"functions Character vector function names load. Defaults functions. stan_path Character string, path Stan code. Defaults path Stan code primarycensoreddist package. wrap_in_block Logical, whether wrap functions functions{} block. Default FALSE. write_to_file Logical, whether write output file. Default FALSE. output_file Character string, path write output file write_to_file TRUE. Defaults \"pcd_functions.stan\".","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"character string containing requested Stan functions","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":null,"dir":"Reference","previous_headings":"","what":"Get Stan files containing specified functions — pcd_stan_files","title":"Get Stan files containing specified functions — pcd_stan_files","text":"function retrieves Stan files specified directory, optionally filtering files contain specific functions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get Stan files containing specified functions — pcd_stan_files","text":"","code":"pcd_stan_files( functions = NULL, stan_path = primarycensoreddist::pcd_stan_path() )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get Stan files containing specified functions — pcd_stan_files","text":"functions Character vector function names search . NULL, Stan files returned. stan_path Character string specifying path directory containing Stan files. Defaults Stan path primarycensoreddist package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get Stan files containing specified functions — pcd_stan_files","text":"character vector file paths Stan files.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Get Stan function names from Stan files — pcd_stan_functions","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"function reads Stan files specified directory extracts names functions defined files.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"","code":"pcd_stan_functions(stan_path = primarycensoreddist::pcd_stan_path())"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"stan_path Character string specifying path directory containing Stan files. Defaults Stan path primarycensoreddist package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"character vector containing unique names functions found Stan files.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_path.html","id":null,"dir":"Reference","previous_headings":"","what":"Get the path to the Stan code — pcd_stan_path","title":"Get the path to the Stan code — pcd_stan_path","text":"Get path Stan code","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_path.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get the path to the Stan code — pcd_stan_path","text":"","code":"pcd_stan_path()"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_path.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get the path to the Stan code — pcd_stan_path","text":"character string path Stan code","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute the primary event censored CDF for delays — pprimarycensoreddist","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"function computes primary event censored cumulative distribution function (CDF) given set quantiles. adjusts CDF primary event distribution accounting delay distribution potential truncation maximum delay (D). function allows custom primary event distributions delay distributions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"","code":"pprimarycensoreddist( q, pdist, pwindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), ... ) ppcens( q, pdist, pwindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), ... )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"q Vector quantiles pdist Distribution function (CDF) pwindow Primary event window D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. dprimary Function generate probability density function (PDF) primary event times. function take value x pwindow parameter, return probability density. normalized integrate 1 [0, pwindow]. Defaults uniform distribution [0, pwindow]. Users can provide custom functions use helper functions like dexpgrowth exponential growth distribution. See primary_dists.R examples. dprimary_args List additional arguments passed dprimary. example, using dexpgrowth, pass list(min = 0, max = pwindow, r = 0.2) set minimum, maximum, rate parameters. ... Additional arguments passed pdist","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"Vector primary event censored CDFs, normalized D finite (truncation adjustment)","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"primary event censored CDF computed integrating product primary event distribution function (CDF) delay distribution function (PDF) primary event window. integration adjusted truncation finite maximum delay (D) specified. primary event censored CDF, \\(F_{\\text{cens}}(q)\\), given : $$ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} F(q - p) \\cdot f_{\\text{primary}}(p) \\, dp $$ \\(F\\) CDF primary event distribution, \\(f_{\\text{primary}}\\) PDF primary event times, \\(pwindow\\) primary event window. maximum delay \\(D\\) finite, CDF normalized \\(F(D)\\): $$ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} \\frac{F(q - p)}{F(D - p)} \\cdot f_{\\text{primary}}(p) \\, dp $$","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"","code":"# Example: Lognormal distribution with uniform primary events pprimarycensoreddist(c(0.1, 0.5, 1), plnorm, meanlog = 0, sdlog = 1) #> [1] 0.0002753181 0.0475094631 0.2384217081 # Example: Lognormal distribution with exponential growth primary events pprimarycensoreddist( c(0.1, 0.5, 1), plnorm, dprimary = dexpgrowth, dprimary_args = list(r = 0.2), meanlog = 0, sdlog = 1 ) #> [1] 0.0002496934 0.0440815583 0.2290795695"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"function generates random samples primary event censored distribution. adjusts distribution accounting primary event distribution potential truncation maximum delay (D). function allows custom primary event distributions delay distributions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"","code":"rprimarycensoreddist( n, rdist, pwindow = 1, swindow = 1, D = Inf, rprimary = stats::runif, rprimary_args = list(), oversampling_factor = 1.2, ... ) rpcens( n, rdist, pwindow = 1, swindow = 1, D = Inf, rprimary = stats::runif, rprimary_args = list(), oversampling_factor = 1.2, ... )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"n Number random samples generate. rdist Function generate random samples delay distribution example stats::rlnorm() lognormal distribution. pwindow Primary event window swindow Integer specifying window size rounding delay (default 1). swindow = 0 rounding applied. D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. rprimary Function generate random samples primary distribution (default stats::runif()). rprimary_args List additional arguments passed rprimary. oversampling_factor Factor oversample number samples account truncation (default 1.2). ... Additional arguments passed distribution function.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"Vector random samples primary event censored distribution censored secondary event window.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"mathematical formulation generating random samples primary event censored distribution follows: Generate primary event times (p) specified primary event distribution (f_p) within primary event window (pwindow): $$p \\sim f_p(x), \\quad 0 \\leq x \\leq pwindow$$ Generate delays (d) specified delay distribution (f_d) parameters theta: $$d \\sim f_d(x; \\theta)$$ Calculate total delays (t) adding primary event times delays: $$t = p + d$$ Apply truncation ensure delays within specified range [0, D]: $$t_{truncated} = \\{t \\mid 0 \\leq t < D\\}$$ Round truncated delays nearest secondary event window (swindow): $$t_{valid} = \\lfloor \\frac{t_{truncated}}{swindow} \\rfloor \\times swindow$$ function oversamples account potential truncation generates additional samples needed reach desired number valid samples.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"","code":"# Example: Lognormal distribution with uniform primary events rprimarycensoreddist(10, rlnorm, meanlog = 0, sdlog = 1) #> [1] 1 3 3 1 1 6 1 3 4 1 # Example: Lognormal distribution with exponential growth primary events rprimarycensoreddist( 10, rlnorm, rprimary = rexpgrowth, rprimary_args = list(r = 0.2), meanlog = 0, sdlog = 1 ) #> [1] 1 3 1 0 1 1 2 9 1 1"},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"package-0-1-0-1000","dir":"Changelog","previous_headings":"","what":"Package","title":"primarycensoreddist 0.1.0.1000","text":"Added support swindow = 0 rprimarycensoreddist allow non-secondary event censored distributions. Adapted rprimarycensoreddist truncation based primary censored distribution secondary events censored. better matches generative process. Added new Stan interface tool enable finding files functions implemented Stan code.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"documentation-0-1-0-1000","dir":"Changelog","previous_headings":"","what":"Documentation","title":"primarycensoreddist 0.1.0.1000","text":"Added getting started vignette. Added vignette showcasing use package Stan code cmdstanr.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"primarycensoreddist-010","dir":"Changelog","previous_headings":"","what":"primarycensoreddist 0.1.0","title":"primarycensoreddist 0.1.0","text":"initial primarycensoreddist release includes R stan tools dealing potentially truncated primary event censored delay distributions. expect current features work UI may change package matures next versions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"package-0-1-0","dir":"Changelog","previous_headings":"","what":"Package","title":"primarycensoreddist 0.1.0","text":"Added package skeleton. Added checking input functions. Added stan functions primary censored truncated distributions. Added R functions primary censored truncated distributions. Add R function facilitate working Stan code. Added tests primary censored truncated distributions. Added tests compare R Stan implementations. Added tests R functions facilitate working Stan code. Resolved R CMD check errors, warnings notes. Added hexsticker. Added vignette skeletons preparation 0.2.0 release.","code":""}] +[{"path":"https://primarycensoreddist.epinowcast.org/dev/LICENSE.html","id":null,"dir":"","previous_headings":"","what":"MIT License","title":"MIT License","text":"Copyright (c) 2024 primarycensoreddist authors Permission hereby granted, free charge, person obtaining copy software associated documentation files (“Software”), deal Software without restriction, including without limitation rights use, copy, modify, merge, publish, distribute, sublicense, /sell copies Software, permit persons Software furnished , subject following conditions: copyright notice permission notice shall included copies substantial portions Software. SOFTWARE PROVIDED “”, WITHOUT WARRANTY KIND, EXPRESS IMPLIED, INCLUDING LIMITED WARRANTIES MERCHANTABILITY, FITNESS PARTICULAR PURPOSE NONINFRINGEMENT. EVENT SHALL AUTHORS COPYRIGHT HOLDERS LIABLE CLAIM, DAMAGES LIABILITY, WHETHER ACTION CONTRACT, TORT OTHERWISE, ARISING , CONNECTION SOFTWARE USE DEALINGS SOFTWARE.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/fitting-dists-with-stan.html","id":"what-are-we-going-to-do-in-this-vignette","dir":"Articles","previous_headings":"1 Introduction","what":"What are we going to do in this Vignette","title":"Fitting distributions using primarycensorseddist and cmdstan","text":"vignette, ’ll demonstrate use primarycensoreddist conjunction Stan Bayesian inference epidemiological delay distributions. ’ll cover following key points: Simulating censored delay distribution data Fitting naive model using cmdstan Evaluating naive model’s performance Fitting improved model using primarycensoreddist functionality Comparing primarycensoreddist model’s performance naive model","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/fitting-dists-with-stan.html","id":"what-might-i-need-to-know-before-starting","dir":"Articles","previous_headings":"1 Introduction","what":"What might I need to know before starting","title":"Fitting distributions using primarycensorseddist and cmdstan","text":"vignette builds concepts introduced Getting Started primarycensoreddist vignette assumes familiarity using Stan tools covered use primarycensoreddist Stan vignette.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/fitting-dists-with-stan.html","id":"packages-used-in-this-vignette","dir":"Articles","previous_headings":"1 Introduction","what":"Packages used in this vignette","title":"Fitting distributions using primarycensorseddist and cmdstan","text":"Alongside primarycensoreddist package use cmdstanr package interfacing cmdstan. also use ggplot2 package plotting dplyr data manipulation.","code":"library(primarycensoreddist) library(cmdstanr) library(ggplot2) library(dplyr)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/fitting-dists-with-stan.html","id":"simulating-censored-and-truncated-delay-distribution-data","dir":"Articles","previous_headings":"","what":"Simulating censored and truncated delay distribution data","title":"Fitting distributions using primarycensorseddist and cmdstan","text":"’ll start simulating censored truncated delay distribution data. ’ll use rprimarycensoreddist function (actually use rpcens alias brevity). ’ve aggregated data unique combinations pwindow, swindow, obs_time counted number occurrences observed_delay combination. data use fit model.","code":"set.seed(123) # For reproducibility # Define the true distribution parameters n <- 1000 meanlog <- 1.5 sdlog <- 0.75 # Generate varying pwindow, swindow, and obs_time lengths pwindows <- sample(1, n, replace = TRUE) swindows <- sample(1, n, replace = TRUE) obs_times <- 10 # Function to generate a single sample generate_sample <- function(pwindow, swindow, obs_time) { rpcens( 1, rlnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = swindow, D = obs_time ) } # Generate samples samples <- mapply(generate_sample, pwindows, swindows, obs_times) # Create initial data frame delay_data <- data.frame( pwindow = pwindows, swindow = swindows, obs_time = obs_times, observed_delay = samples ) head(delay_data) ## pwindow swindow obs_time observed_delay ## 1 1 1 10 2 ## 2 1 1 10 1 ## 3 1 1 10 8 ## 4 1 1 10 6 ## 5 1 1 10 5 ## 6 1 1 10 4 # Aggregate to unique combinations and count occurrences # Aggregate to unique combinations and count occurrences delay_counts <- delay_data |> summarise(n = n(), .by = c(pwindow, swindow, obs_time, observed_delay)) head(delay_counts) ## pwindow swindow obs_time observed_delay n ## 1 1 1 10 2 160 ## 2 1 1 10 1 96 ## 3 1 1 10 8 59 ## 4 1 1 10 6 113 ## 5 1 1 10 5 119 ## 6 1 1 10 4 150 # Compare the samples with and without secondary censoring to the true # distribution # Calculate empirical CDF empirical_cdf <- ecdf(samples) # Create a sequence of x values for the theoretical CDF x_seq <- seq(min(samples), max(samples), length.out = 100) # Calculate theoretical CDF theoretical_cdf <- plnorm(x_seq, meanlog = meanlog, sdlog = sdlog) # Create a long format data frame for plotting cdf_data <- data.frame( x = rep(x_seq, 2), probability = c(empirical_cdf(x_seq), theoretical_cdf), type = rep(c(\"Observed\", \"Theoretical\"), each = length(x_seq)), stringsAsFactors = FALSE ) # Plot ggplot(cdf_data, aes(x = x, y = probability, color = type)) + geom_step(linewidth = 1) + scale_color_manual( values = c(Observed = \"#4292C6\", Theoretical = \"#252525\") ) + geom_vline( aes(xintercept = mean(samples), color = \"Observed\"), linetype = \"dashed\", linewidth = 1 ) + geom_vline( aes(xintercept = exp(meanlog + sdlog^2 / 2), color = \"Theoretical\"), linetype = \"dashed\", linewidth = 1 ) + labs( title = \"Comparison of Observed vs Theoretical CDF\", x = \"Delay\", y = \"Cumulative Probability\", color = \"CDF Type\" ) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5), legend.position = \"bottom\" )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/fitting-dists-with-stan.html","id":"fitting-a-naive-model-using-cmdstan","dir":"Articles","previous_headings":"","what":"Fitting a naive model using cmdstan","title":"Fitting distributions using primarycensorseddist and cmdstan","text":"’ll start fitting naive model using cmdstan. ’ll use cmdstanr package interface cmdstan. define model string write file use primarycensoreddist Stan vignette. Now let’s compile model now let’s fit compiled model. see model converged diagnostics look good. However, just model posterior summary see might happy fit. mu smaller target 1.5 sigma larger target 0.75.","code":"writeLines( \"data { int N; // number of observations vector[N] y; // observed delays vector[N] n; // number of occurrences for each delay } parameters { real mu; real sigma; } model { // Priors mu ~ normal(1, 1); sigma ~ normal(0.5, 1); // Likelihood target += n .* lognormal_lpdf(y | mu, sigma); }\", con = file.path(tempdir(), \"naive_lognormal.stan\") ) naive_model <- cmdstan_model(file.path(tempdir(), \"naive_lognormal.stan\")) naive_fit <- naive_model$sample( data = list( # Add a small constant to avoid log(0) y = delay_counts$observed_delay + 1e-6, n = delay_counts$n, N = nrow(delay_counts) ), chains = 4, parallel_chains = 4, show_messages = FALSE, refresh = 0 ) naive_fit ## Warning: NAs introduced by coercion ## variable mean median sd mad q5 q95 rhat ess_bulk ## lp__ -28480.45 -28480.10 1.00 0.74 -28482.40 -28479.50 1.00 1999 ## mu -0.10 -0.10 0.05 0.04 -0.18 -0.02 1.00 2691 ## sigma 4.61 4.61 0.03 0.03 4.56 4.67 1.00 3820 ## ess_tail ## NA ## 2310 ## 2869"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/fitting-dists-with-stan.html","id":"fitting-an-improved-model-using-primarycensoreddist","dir":"Articles","previous_headings":"","what":"Fitting an improved model using primarycensoreddist","title":"Fitting distributions using primarycensorseddist and cmdstan","text":"’ll now fit improved model using primarycensoreddist package. main improvement use primary_censored_dist_lpdf function fit model. Stan version pcens() function accounts primary secondary censoring windows well truncation. encode primary distribution lognormal distribution passing 1 dist_id parameter primary event distribution uniform passing 1 primary_dist_id parameter. See Stan documentation details primary_censored_dist_lpdf function. Now let’s compile model Now let’s fit compiled model. see model converged diagnostics look good. also see posterior means near true parameters 90% credible intervals include true parameters.","code":"writeLines( \" functions { #include primary_censored_dist.stan #include expgrowth.stan } data { int N; // number of observations array[N] int y; // observed delays array[N] int n; // number of occurrences for each delay array[N] int pwindow; // primary censoring window array[N] int swindow; // secondary censoring window array[N] int D; // maximum delay } transformed data { array[0] real primary_params; } parameters { real mu; real sigma; } model { // Priors mu ~ normal(1, 1); sigma ~ normal(0.5, 0.5); // Likelihood for (i in 1:N) { target += n[i] * primary_censored_dist_lpmf( y[i] | 1, {mu, sigma}, pwindow[i], swindow[i], D[i], 1, primary_params ); } }\", con = file.path(tempdir(), \"primarycensoreddist_lognormal.stan\") ) primarycensoreddist_model <- cmdstan_model( file.path(tempdir(), \"primarycensoreddist_lognormal.stan\"), include_paths = pcd_stan_path() ) primarycensoreddist_fit <- primarycensoreddist_model$sample( data = list( y = delay_counts$observed_delay, n = delay_counts$n, pwindow = delay_counts$pwindow, swindow = delay_counts$swindow, D = delay_counts$obs_time, N = nrow(delay_counts) ), chains = 4, parallel_chains = 4, init = list( # we use this to resolve initialisation issues list(mu = 1.5, sigma = 0.6), list(mu = 1.5, sigma = 0.4), list(mu = 1.5, sigma = 0.3), list(mu = 1.5, sigma = 0.55) ), refresh = 0, show_messages = FALSE ) primarycensoreddist_fit ## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail ## lp__ -2134.42 -2134.13 0.97 0.70 -2136.43 -2133.49 1.00 732 952 ## mu 1.53 1.53 0.05 0.05 1.46 1.61 1.01 620 686 ## sigma 0.77 0.77 0.04 0.04 0.71 0.83 1.00 633 641"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"introduction","dir":"Articles","previous_headings":"","what":"Introduction","title":"Getting Started with primarycensoreddist","text":"Delay distributions play crucial role various fields, including epidemiology, reliability analysis, survival analysis. distributions describe time two events interest, incubation period disease time failure component. Accurately estimating calculating distributions essential understanding underlying processes making informed decisions[1]. However, estimating distributions can challenging due various factors, including censoring truncation observed data[2]. estimation delay distributions often faces following challenges: Primary event censoring: primary event (e.g., exposure pathogen start process) often observed degree interval censoring. means exact time event known, rather, known occurred within certain time interval, commonly day. result, distribution based primary events combination underlying true distribution censoring distribution. Truncation: observation delay distributions often conditioned occurrence secondary event. leads truncation observed distribution, delays longer observation time captured data. Consequently, observed distribution combination underlying true distribution, censoring distribution, observation time. Secondary event censoring: secondary event (e.g., symptom onset end process) also frequently observed interval censoring. additional layer censoring complicates estimation delay distribution. primarycensoreddist package aims address challenges providing tools manipulate primary censored delay distributions. accounting censoring truncation present data, package enables accurate estimation use underlying true distribution. vignette, provide quick introduction main functions concepts primarycensoreddist package. cover mathematical formulation problem, demonstrate usage key functions, provide signposting learn .","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"packages-in-this-getting-started-vignette-","dir":"Articles","previous_headings":"","what":"Packages in this getting started vignette.","title":"Getting Started with primarycensoreddist","text":"well primarycensoreddist package vignette also uses ggplot2.","code":"# Load packages library(primarycensoreddist) library(ggplot2) # Set seed for reproducibility set.seed(123)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"generating-random-samples-with-rprimarycensoreddist","dir":"Articles","previous_headings":"","what":"Generating Random Samples with rprimarycensoreddist()","title":"Getting Started with primarycensoreddist","text":"function generates random samples primary event censored distribution. adjusts distribution accounting primary event distribution, potential truncation maximum delay (D), secondary event censoring. mathematical formulation generating random samples primary event censored distribution follows: Generate primary event times (\\(p\\)) specified primary event distribution (\\(f_p\\)) within primary event window (\\(pwindow\\)): \\[p \\sim f_p(x), \\quad 0 \\leq x \\leq pwindow\\] Generate delays (\\(d\\)) specified delay distribution (\\(f_d\\)) parameters \\(\\theta\\): \\[d \\sim f_d(x; \\theta)\\] Calculate total delays (\\(t\\)) adding primary event times delays: \\[t = p + d\\] Apply truncation ensure delays within specified range \\([0, D]\\): \\[t_{truncated} = \\{t \\mid 0 \\leq t < D\\}\\] Round truncated delays nearest secondary event window (\\(swindow\\)): \\[t_{valid} = \\lfloor \\frac{t_{truncated}}{swindow} \\rfloor \\times swindow\\] ’s example use rprimarycensoreddist() sample log-normal distribution without secondary interval censoring. simplicity use daily secondary censoring window events. Neither distribution matches true distribution due truncation D biases observed distributions towards shorter delays primary secondary event censoring.","code":"n <- 1e4 meanlog <- 1.5 sdlog <- 0.75 obs_time <- 10 pwindow <- 1 # Random samples without secondary censoring samples <- rprimarycensoreddist( n, rlnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = 0, D = obs_time ) # Random samples with secondary censoring samples_sc <- rprimarycensoreddist( n, rlnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = 1, D = obs_time ) # Calculate the PMF for the samples with secondary censoring samples_sc_pmf <- data.frame( pmf = table(samples_sc) / sum(table(samples_sc)) ) # Compare the samples with and without secondary censoring to the true # distribution ggplot() + geom_density( data = data.frame(samples = samples), aes(x = samples), fill = \"#4292C6\", col = \"#252525\", alpha = 0.5 ) + geom_col( data = samples_sc_pmf, aes( x = as.numeric(as.character(pmf.samples_sc)), y = pmf.Freq ), fill = \"#20b986\", col = \"#252525\", alpha = 0.5, width = 0.9, just = 0 ) + geom_function( fun = dlnorm, args = list(meanlog = meanlog, sdlog = sdlog), color = \"#252525\", linewidth = 1 ) + labs( title = \"Comparison of Samples from Log-Normal Distribution\", x = \"Samples\", y = \"Density\", caption = paste0( \"Blue density: Samples without secondary censoring\\n\", \"Green bars: Samples with secondary censoring\\n\", \"Black line: True log-normal distribution without truncation\" ) ) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5) )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"compute-the-primary-event-censored-cumulative-distribution-function-cdf-for-delays-with-pprimarycensoreddist","dir":"Articles","previous_headings":"","what":"Compute the primary event censored cumulative distribution function (CDF) for delays with pprimarycensoreddist()","title":"Getting Started with primarycensoreddist","text":"function computes primary event censored cumulative distribution function (CDF) given set quantiles. adjusts CDF delay distribution accounting primary event distribution potential truncation maximum delay (D). primary event censored CDF, (\\(F_{\\text{cens}}(q)\\)), given : \\[ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} F(q - p) \\cdot f_{\\text{primary}}(p) \\, dp \\] (\\(F\\)) CDF primary event distribution, (\\(f_{\\text{primary}}\\)) PDF primary event times, (\\(pwindow\\)) primary event window. maximum delay (\\(D\\)) finite, CDF normalized (\\(F(D)\\)): \\[ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} \\frac{F(q - p)}{F(D - p)} \\cdot f_{\\text{primary}}(p) \\, dp \\] Let’s compare empirical CDF samples without secondary censoring theoretical CDF computed using pprimarycensoreddist(): theoretical CDF matches empirical CDF well, confirming pprimarycensoreddist() working expected.","code":"empirical_cdf <- ecdf(samples) theoretical_cdf <- pprimarycensoreddist( seq(0, obs_time, length.out = 100), plnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, D = obs_time ) # Create a data frame for plotting cdf_data <- data.frame( x = seq(0, obs_time, length.out = 100), Theoretical = theoretical_cdf, Empirical = empirical_cdf(seq(0, obs_time, length.out = 100)) ) # Plot the empirical and theoretical CDFs ggplot(cdf_data, aes(x = x)) + geom_step(aes(y = Theoretical), color = \"black\", linewidth = 1) + geom_step(aes(y = Empirical), color = \"#4292C6\", linewidth = 1) + labs( title = \"Comparison of Empirical and Theoretical CDFs\", x = \"Delay\", y = \"Cumulative Probability\", caption = paste0( \"Blue line: Empirical CDF from samples without secondary censoring\\n\", \"Black line: Theoretical CDF computed using pprimarycensoreddist()\" ) ) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5) )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"compute-the-primary-event-censored-probability-mass-function-pmfwith-dprimarycensoreddist","dir":"Articles","previous_headings":"","what":"Compute the primary event censored probability mass function (PMF)with dprimarycensoreddist()","title":"Getting Started with primarycensoreddist","text":"function computes primary event censored probability mass function (PMF) given set quantiles using CDF. top accounting primary event distribution truncation also accounts secondary event censoring. primary event censored PMF, (\\(f_{\\text{cens}}(d)\\)), given : \\[ f_{\\text{cens}}(d) = F_{\\text{cens}}(d + \\text{swindow}) - F_{\\text{cens}}(d) \\] (\\(F_{\\text{cens}}\\)) potentially right truncated primary event censored CDF (\\(\\text{swindow}\\)) secondary event window. Let’s compare empirical PMF samples secondary censoring theoretical PMF computed using dprimarycensoreddist(): theoretical PMF matches empirical PMF well, confirming dprimarycensoreddist() also working expected.","code":"# Calculate the theoretical PMF using dprimarycensoreddist theoretical_pmf <- dprimarycensoreddist( 0:(obs_time - 1), plnorm, meanlog = meanlog, sdlog = sdlog, pwindow = pwindow, swindow = 1, D = obs_time ) pmf_df <- data.frame( x = 0:obs_time, pmf = c(theoretical_pmf, 0) ) # Plot the empirical and theoretical PMFs ggplot() + geom_col( data = samples_sc_pmf, aes( x = as.numeric(as.character(pmf.samples_sc)), y = pmf.Freq ), fill = \"#20b986\", col = \"#252525\", alpha = 0.5, width = 0.9, just = 0 ) + geom_step( data = pmf_df, aes(x = x, y = pmf), color = \"black\", linewidth = 1 ) + labs( title = \"Comparison of Samples from Log-Normal Distribution\", x = \"Samples\", y = \"Density\", caption = paste0( \"Green bars: Empirical PMF from samples with secondary censoring\\n\", \"Black line: Theoretical PMF computed using dprimarycensoreddist()\" ) ) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_minimal() + theme( panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5) )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"other-key-functionality","dir":"Articles","previous_headings":"","what":"Other key functionality","title":"Getting Started with primarycensoreddist","text":"addition main functions, package also includes: Primary event distributions: package includes commonly used primary event distributions exponential growth. Stan versions functions R functions interface Stan: R functions corresponding Stan function. Stan functions used estimation delay distributions using Stan software. package also includes tools manipulate Stan code R.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/primarycensoreddist.html","id":"learning-more","dir":"Articles","previous_headings":"","what":"Learning more","title":"Getting Started with primarycensoreddist","text":"primarycensoreddist see package vignettes function documentation. methodological background delay distributions see Park et al.[2]. advice best practices estimating handling delay distributions see Charniga et al.[1].","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"what-are-we-going-to-do-in-this-vignette","dir":"Articles","previous_headings":"1 Introduction","what":"What are we going to do in this Vignette","title":"How to use primarycensoreddist with Stan","text":"vignette, ’ll explore use primarycensoreddist package conjunction Stan. ’ll cover following key points: Introduction Stan relevance analysis Overview packages ’ll using access use Stan functions provided primarycensoreddist Methods integrating Stan functions workflow","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"what-is-stan-and-why-are-we-using-it","dir":"Articles","previous_headings":"1 Introduction","what":"What is Stan and why are we using it","title":"How to use primarycensoreddist with Stan","text":"Stan probabilistic programming language statistical inference. provides flexible efficient platform Bayesian modeling widely used various fields data science statistics. vignette, ’ll use Stan conjunction primarycensoreddist perform Bayesian inference censored data. information Stan: Stan’s official website Stan documentation Stan forums community support discussions","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"packages-used-in-this-vignette","dir":"Articles","previous_headings":"1 Introduction","what":"Packages used in this vignette","title":"How to use primarycensoreddist with Stan","text":"Alongside primarycensoreddist package use cmdstanr package interfacing cmdstan.","code":"library(primarycensoreddist) library(cmdstanr)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"using-stan-code-in-primarycensoreddist","dir":"Articles","previous_headings":"","what":"Using Stan code in primarycensoreddist","title":"How to use primarycensoreddist with Stan","text":"primarycensoreddist includes set Stan functions mirror R functions primarycensoreddist. Documentation functions can found . support range approaches integrate Stan code workflow.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"checking-available-stan-functions-using-pcd_stan_functions","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist","what":"Checking available Stan functions using pcd_stan_functions()","title":"How to use primarycensoreddist with Stan","text":"Aside reading documentation also possible list available Stan functions using helper function directly R.","code":"pcd_stan_functions() ## [1] \"expgrowth_pdf\" ## [2] \"expgrowth_lpdf\" ## [3] \"expgrowth_cdf\" ## [4] \"expgrowth_lcdf\" ## [5] \"expgrowth_rng\" ## [6] \"dist_lcdf\" ## [7] \"primary_dist_lpdf\" ## [8] \"primary_censored_integrand\" ## [9] \"primary_censored_dist_cdf\" ## [10] \"primary_censored_dist_lcdf\" ## [11] \"primary_censored_dist_lpmf\" ## [12] \"primary_censored_dist_pmf\" ## [13] \"primary_censored_sone_lpmf_vectorized\" ## [14] \"primary_censored_sone_pmf_vectorized\""},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"accessing-stan-functions","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist","what":"Accessing Stan functions","title":"How to use primarycensoreddist with Stan","text":"Stan functions accessed using pcd_load_stan_functions() function. function takes name function argument returns function string. can additionally write functions file wrap functions{} block.","code":"pcd_load_stan_functions(\"primary_censored_dist_lpmf\") ## [1] \"// Stan functions from primarycensoreddist version 0.2.0.1000\\nreal primary_censored_dist_lpmf(int d, int dist_id, array[] real params,\\n data real pwindow, real swindow, data real D,\\n int primary_dist_id, array[] real primary_params) {\\n\\n real d_upper = d + swindow;\\n if (d_upper > D) {\\n reject(\\\"Upper truncation point is greater than D. It is \\\", d_upper,\\n \\\" and D is \\\", D, \\\". Resolve this by increasing D to be greater or equal to d + swindow.\\\");\\n }\\n real log_cdf_upper = primary_censored_dist_lcdf(\\n d_upper | dist_id, params, pwindow, D, primary_dist_id, primary_params\\n );\\n real log_cdf_lower = primary_censored_dist_lcdf(\\n d | dist_id, params, pwindow, D, primary_dist_id, primary_params\\n );\\n return log_diff_exp(log_cdf_upper, log_cdf_lower);\\n}\""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"writing-functions-to-a-file","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist > 2.3 Linking the Stan functions to your workflow","what":"Writing functions to a file","title":"How to use primarycensoreddist with Stan","text":"One option using Stan functions write file compile using cmdstanr. good approach means functions written can used way stan functions might use. downside may mean work keeping date changes functions. can using pcd_load_stan_functions() function. can now compiled used way cmdstanr model. Alternatively, use #include expgrowth_rng.stan stan file functions block include function along path file stan file (see ).","code":"expgrowth_rng_file <- file.path(tempdir(), \"expgrowth_rng.stan\") exp_model <- pcd_load_stan_functions( \"expgrowth_rng\", write_to_file = TRUE, output_file = expgrowth_rng_file, wrap_in_block = TRUE ) ## Stan functions written to: /tmp/RtmpaPzbyH/expgrowth_rng.stan model <- cmdstan_model(expgrowth_rng_file) model ## functions { ## // Stan functions from primarycensoreddist version 0.2.0.1000 ## real expgrowth_rng(real min, real max, real r) { ## real u = uniform_rng(0, 1); ## if (abs(r) < 1e-10) { ## return min + u * (max - min); ## } ## return min + log(u * (exp(r * max) - exp(r * min)) + exp(r * min)) / r; ## } ## }"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"including-the-functions-directly-via-include_paths","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist > 2.3 Linking the Stan functions to your workflow","what":"Including the functions directly via include_paths","title":"How to use primarycensoreddist with Stan","text":"Rather writing functions file also possible include directly stan file using include_paths argument cmdstan_model(). useful don’t clutter model stan code primarycensoreddist want automatic updating functions. demonstrate first write small model expgrowth.stan include paths (rather writing file including ). first step find file path expgrowth_rng function. done now write stan wrapper model. can now use file compile model. Note need include path primarycensoreddist Stan functions using include_paths argument cmdstan_model(). can sample model (set fixed_param = TRUE toy example doesn’t require MCMC sampling).","code":"pcd_stan_files(\"expgrowth_rng\") ## [1] \"expgrowth.stan\" expgrowth_stan_file <- file.path(tempdir(), \"expgrowth.stan\") writeLines( text = c( \"functions {\", \"#include expgrowth.stan\", \"}\", \"generated quantities {\", \" real y = expgrowth_rng(0, 1, 0.4);\", \"}\" ), con = expgrowth_stan_file ) model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) model ## functions { ## #include expgrowth.stan ## } ## generated quantities { ## real y = expgrowth_rng(0, 1, 0.4); ## } samples <- model$sample(chains = 1, fixed_param = TRUE) ## Running MCMC with 1 chain... ## ## Chain 1 Iteration: 1 / 1000 [ 0%] (Sampling) ## Chain 1 Iteration: 100 / 1000 [ 10%] (Sampling) ## Chain 1 Iteration: 200 / 1000 [ 20%] (Sampling) ## Chain 1 Iteration: 300 / 1000 [ 30%] (Sampling) ## Chain 1 Iteration: 400 / 1000 [ 40%] (Sampling) ## Chain 1 Iteration: 500 / 1000 [ 50%] (Sampling) ## Chain 1 Iteration: 600 / 1000 [ 60%] (Sampling) ## Chain 1 Iteration: 700 / 1000 [ 70%] (Sampling) ## Chain 1 Iteration: 800 / 1000 [ 80%] (Sampling) ## Chain 1 Iteration: 900 / 1000 [ 90%] (Sampling) ## Chain 1 Iteration: 1000 / 1000 [100%] (Sampling) ## Chain 1 finished in 0.0 seconds. samples ## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail ## y 0.51 0.52 0.29 0.38 0.06 0.95 1.00 1065 983"},{"path":"https://primarycensoreddist.epinowcast.org/dev/articles/using-stan-tools.html","id":"using-stan-functions-directly-in-r","dir":"Articles","previous_headings":"2 Using Stan code in primarycensoreddist","what":"Using Stan functions directly in R","title":"How to use primarycensoreddist with Stan","text":"Whilst possible use Stan functions directly R recommended use cases (use R functions primarycensoreddist instead). However, can useful understand going hood exploration (indeed use internally primarycensoreddist check functions R implementations). use expose_functions() method already compiled model. can now use function R. Note may get slightly complicated stan function depends stan functions (.e. need included compiled model well).","code":"model$expose_functions(global = TRUE) expgrowth_rng(0, 1, 0.4) ## [1] 0.6524848"},{"path":"https://primarycensoreddist.epinowcast.org/dev/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Sam Abbott. Author, maintainer.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Abbott S (2024). primarycensoreddist: Primary Event Censored Distributions R Stan. doi:10.5281/zenodo.13632839.","code":"@Manual{, title = {primarycensoreddist: Primary Event Censored Distributions in R and Stan}, author = {Sam Abbott}, year = {2024}, doi = {10.5281/zenodo.13632839}, }"},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"summary","dir":"","previous_headings":"","what":"Summary","title":"Primary Event Censored Distributions in R and Stan","text":"package provides R functions working primary event censored distributions Stan implementations use Bayesian modeling. Primary event censored distributions useful modeling delayed reporting scenarios epidemiology fields. provides support arbitrary delay distributions, range common primary distributions, allows truncation secondary event censoring accounted .","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Primary Event Censored Distributions in R and Stan","text":"can install latest released version using normal R function, though need point r-universe instead CRAN: Alternatively, can use remotes package install development version Github (warning! version may contain breaking changes /bugs): Similarly, can install historical versions specifying release tag (e.g. installs 0.2.0): Note: can also use last approach install specific commit needed, e.g. want try specific unreleased feature, absolute latest developmental version. wish use Stan functions, need install CmdStan, also entails suitable C++ toolchain setup. recommend using cmdstanr package. Stan team provides instructions Getting started cmdstanr vignette, details support package site along key instructions available Stan resources package vignette, brief version : Note: can speed CmdStan installation using cores argument. installing particular version epinowcast, may also need install past version CmdStan, can version argument.","code":"install.packages( \"primarycensoreddist\", repos = \"https://epinowcast.r-universe.dev\" ) remotes::install_github( \"epinowcast/primarycensoreddist\", dependencies = TRUE ) remotes::install_github( \"epinowcast/primarycensoreddist\", dependencies = TRUE, ref = \"v0.2.0\" ) # if you not yet installed `primarycensoreddist`, or you installed it without # `Suggests` dependencies install.packages( \"cmdstanr\", repos = c(\"https://stan-dev.r-universe.dev\", getOption(\"repos\")) ) # once `cmdstanr` is installed: cmdstanr::install_cmdstan()"},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"resources","dir":"","previous_headings":"","what":"Resources","title":"Primary Event Censored Distributions in R and Stan","text":"provide range documentation, case studies, community spaces ask (answer!) questions: primarycensoreddist website includes function reference, model outline, case studies using package. site mainly concerns release version, can also find documentation latest development version. created package vignettes help get started primarycensoreddist highlight features case studies. organisation website includes links resources, guest posts, seminar schedule upcoming past recordings. community forum areas question answer considering new methods tools, among others. generally interested real-time analysis infectious disease, may find useful even use primarycensoreddist.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"contributing","dir":"","previous_headings":"","what":"Contributing","title":"Primary Event Censored Distributions in R and Stan","text":"welcome contributions new contributors! particularly appreciate help identifying identified issues. Please check add issues, /add pull request see contributing guide information. need different underlying model work: primarycensoreddist provides flexible framework censored distributions R Stan. implement new distributions censoring mechanisms expand overall flexibility improve defaults, please let us know either community forum. always like hear new use-cases extensions package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"how-to-make-a-bug-report-or-feature-request","dir":"","previous_headings":"Contributing","what":"How to make a bug report or feature request","title":"Primary Event Censored Distributions in R and Stan","text":"Please briefly describe problem output expect issue. question, please don’t open issue. Instead, ask Q page. See contributing guide information.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"code-of-conduct","dir":"","previous_headings":"Contributing","what":"Code of Conduct","title":"Primary Event Censored Distributions in R and Stan","text":"Please note primarycensoreddist project released Contributor Code Conduct. contributing project, agree abide terms.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Primary Event Censored Distributions in R and Stan","text":"making use methodology methodology based, please cite relevant papers methods outline. use primarycensoreddist work, please consider citing citation(\"primarycensoreddist\").","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"contributors","dir":"","previous_headings":"","what":"Contributors","title":"Primary Event Censored Distributions in R and Stan","text":"contributions project gratefully acknowledged using allcontributors package following -contributors specification. Contributions kind welcome!","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"code","dir":"","previous_headings":"Contributors","what":"Code","title":"Primary Event Censored Distributions in R and Stan","text":"seabbs","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"issue-authors","dir":"","previous_headings":"Contributors","what":"Issue Authors","title":"Primary Event Censored Distributions in R and Stan","text":"zsusswein, SamuelBrand1","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/index.html","id":"issue-contributors","dir":"","previous_headings":"Contributors","what":"Issue Contributors","title":"Primary Event Censored Distributions in R and Stan","text":"athowes","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":null,"dir":"Reference","previous_headings":"","what":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"function tests whether given function behaves like valid PDF checking integrates approximately 1 specified range takes arguments min max.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"","code":"check_dprimary(dprimary, pwindow, dprimary_args = list(), tolerance = 0.001)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"dprimary Function generate probability density function (PDF) primary event times. function take value x pwindow parameter, return probability density. normalized integrate 1 [0, pwindow]. Defaults uniform distribution [0, pwindow]. Users can provide custom functions use helper functions like dexpgrowth exponential growth distribution. See primary_dists.R examples. pwindow Primary event window dprimary_args List additional arguments passed dprimary. example, using dexpgrowth, pass list(min = 0, max = pwindow, r = 0.2) set minimum, maximum, rate parameters. tolerance tolerance integral considered close 1","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"NULL. function stop execution error message dprimary valid PDF.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_dprimary.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Check if a function is a valid bounded probability density function (PDF) — check_dprimary","text":"","code":"check_dprimary(dunif, pwindow = 1)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":null,"dir":"Reference","previous_headings":"","what":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"function tests whether given function behaves like valid CDF checking monotonically increasing bounded 0 1.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"","code":"check_pdist(pdist, D, ...)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"pdist Distribution function (CDF) D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. ... Additional arguments passed pdist","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"NULL. function stop execution error message pdist valid CDF.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/check_pdist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Check if a function is a valid cumulative distribution function (CDF) — check_pdist","text":"","code":"check_pdist(pnorm, D = 10)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract function names or content from Stan code — .extract_stan_functions","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"Extract function names content Stan code","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"","code":".extract_stan_functions(content, names_only = FALSE, functions = NULL)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"content Character vector containing Stan code names_only Logical, TRUE extract function names, otherwise extract function content. functions Optional, character vector function names extract content .","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dot-extract_stan_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Extract function names or content from Stan code — .extract_stan_functions","text":"Character vector function names content","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute the primary event censored PMF for delays — dprimarycensoreddist","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"function computes primary event censored probability mass function (PMF) given set quantiles. adjusts PMF primary event distribution accounting delay distribution potential truncation maximum delay (D). function allows custom primary event distributions delay distributions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"","code":"dprimarycensoreddist( x, pdist, pwindow = 1, swindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), log = FALSE, ... ) dpcens( x, pdist, pwindow = 1, swindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), log = FALSE, ... )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"x Vector quantiles pdist Distribution function (CDF) pwindow Primary event window swindow Secondary event window (default: 1) D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. dprimary Function generate probability density function (PDF) primary event times. function take value x pwindow parameter, return probability density. normalized integrate 1 [0, pwindow]. Defaults uniform distribution [0, pwindow]. Users can provide custom functions use helper functions like dexpgrowth exponential growth distribution. See primary_dists.R examples. dprimary_args List additional arguments passed dprimary. example, using dexpgrowth, pass list(min = 0, max = pwindow, r = 0.2) set minimum, maximum, rate parameters. log Logical; TRUE, probabilities p given log(p) ... Additional arguments passed distribution function","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"Vector primary event censored PMFs, normalized D finite (truncation adjustment)","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"primary event censored PMF computed taking difference primary event censored cumulative distribution function (CDF) two points, \\(d + \\text{swindow}\\) \\(d\\). primary event censored PMF, \\(f_{\\text{cens}}(d)\\), given : $$ f_{\\text{cens}}(d) = F_{\\text{cens}}(d + \\text{swindow}) - F_{\\text{cens}}(d) $$ \\(F_{\\text{cens}}\\) primary event censored CDF. explanation mathematical details CDF, refer documentation pprimarycensoreddist().","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/dprimarycensoreddist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute the primary event censored PMF for delays — dprimarycensoreddist","text":"","code":"# Example: Weibull distribution with uniform primary events dprimarycensoreddist(c(0.1, 0.5, 1), pweibull, shape = 1.5, scale = 2.0) #> [1] 0.1577952 0.2735269 0.3463199 # Example: Weibull distribution with exponential growth primary events dprimarycensoreddist( c(0.1, 0.5, 1), pweibull, dprimary = dexpgrowth, dprimary_args = list(r = 0.2), shape = 1.5, scale = 2.0 ) #> [1] 0.1522796 0.2691280 0.3459055"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":null,"dir":"Reference","previous_headings":"","what":"Exponential growth distribution functions — expgrowth","title":"Exponential growth distribution functions — expgrowth","text":"Density, distribution function, random generation exponential growth distribution.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Exponential growth distribution functions — expgrowth","text":"","code":"dexpgrowth(x, min = 0, max = 1, r, log = FALSE) pexpgrowth(q, min = 0, max = 1, r, lower.tail = TRUE, log.p = FALSE) rexpgrowth(n, min = 0, max = 1, r)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Exponential growth distribution functions — expgrowth","text":"x, q Vector quantiles. min Minimum value distribution range. Default 0. max Maximum value distribution range. Default 1. r Rate parameter exponential growth. log, log.p Logical; TRUE, probabilities p given log(p). lower.tail Logical; TRUE (default), probabilities P[X ≤ x], otherwise, P[X > x]. n Number observations. length(n) > 1, length taken number required.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Exponential growth distribution functions — expgrowth","text":"dexpgrowth gives density, pexpgrowth gives distribution function, rexpgrowth generates random deviates. length result determined n rexpgrowth, maximum lengths numerical arguments functions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Exponential growth distribution functions — expgrowth","text":"exponential growth distribution defined interval [min, max] rate parameter (r). probability density function (PDF) : $$f(x) = \\frac{r \\cdot \\exp(r \\cdot (x - min))}{\\exp(r \\cdot max) - \\exp(r \\cdot min)}$$ cumulative distribution function (CDF) : $$F(x) = \\frac{\\exp(r \\cdot (x - min)) - \\exp(r \\cdot min)}{ \\exp(r \\cdot max) - \\exp(r \\cdot min)}$$ random number generation, use inverse transform sampling method: Generate \\(u \\sim \\text{Uniform}(0,1)\\) Set \\(F(x) = u\\) solve \\(x\\): $$ x = min + \\frac{1}{r} \\cdot \\log(u \\cdot (\\exp(r \\cdot max) - \\exp(r \\cdot min)) + \\exp(r \\cdot min)) $$ method works probability integral transform theorem, states \\(X\\) continuous random variable CDF \\(F(x)\\), \\(Y = F(X)\\) follows \\(\\text{Uniform}(0,1)\\) distribution. Conversely, \\(U\\) \\(\\text{Uniform}(0,1)\\) random variable, \\(F^{-1}(U)\\) distribution \\(X\\), \\(F^{-1}\\) inverse CDF. case, generate \\(u\\) \\(\\text{Uniform}(0,1)\\), solve \\(F(x) = u\\) \\(x\\) get sample exponential growth distribution. formula \\(x\\) derived algebraically solving equation: $$ u = \\frac{\\exp(r \\cdot (x - min)) - \\exp(r \\cdot min)}{\\exp(r \\cdot max) - \\exp(r \\cdot min)} $$ \\(r\\) close 0 (\\(|r| < 1e-10\\)), distribution approximates uniform distribution [min, max], use simpler method generate samples directly uniform distribution.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/expgrowth.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Exponential growth distribution functions — expgrowth","text":"","code":"x <- seq(0, 1, by = 0.1) probs <- dexpgrowth(x, r = 0.2) cumprobs <- pexpgrowth(x, r = 0.2) samples <- rexpgrowth(100, r = 0.2)"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Load Stan functions as a string — pcd_load_stan_functions","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"Load Stan functions string","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"","code":"pcd_load_stan_functions( functions = NULL, stan_path = primarycensoreddist::pcd_stan_path(), wrap_in_block = FALSE, write_to_file = FALSE, output_file = \"pcd_functions.stan\" )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"functions Character vector function names load. Defaults functions. stan_path Character string, path Stan code. Defaults path Stan code primarycensoreddist package. wrap_in_block Logical, whether wrap functions functions{} block. Default FALSE. write_to_file Logical, whether write output file. Default FALSE. output_file Character string, path write output file write_to_file TRUE. Defaults \"pcd_functions.stan\".","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_load_stan_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Load Stan functions as a string — pcd_load_stan_functions","text":"character string containing requested Stan functions","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":null,"dir":"Reference","previous_headings":"","what":"Get Stan files containing specified functions — pcd_stan_files","title":"Get Stan files containing specified functions — pcd_stan_files","text":"function retrieves Stan files specified directory, optionally filtering files contain specific functions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get Stan files containing specified functions — pcd_stan_files","text":"","code":"pcd_stan_files( functions = NULL, stan_path = primarycensoreddist::pcd_stan_path() )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get Stan files containing specified functions — pcd_stan_files","text":"functions Character vector function names search . NULL, Stan files returned. stan_path Character string specifying path directory containing Stan files. Defaults Stan path primarycensoreddist package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_files.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get Stan files containing specified functions — pcd_stan_files","text":"character vector file paths Stan files.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Get Stan function names from Stan files — pcd_stan_functions","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"function reads Stan files specified directory extracts names functions defined files.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"","code":"pcd_stan_functions(stan_path = primarycensoreddist::pcd_stan_path())"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"stan_path Character string specifying path directory containing Stan files. Defaults Stan path primarycensoreddist package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get Stan function names from Stan files — pcd_stan_functions","text":"character vector containing unique names functions found Stan files.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_path.html","id":null,"dir":"Reference","previous_headings":"","what":"Get the path to the Stan code — pcd_stan_path","title":"Get the path to the Stan code — pcd_stan_path","text":"Get path Stan code","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_path.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get the path to the Stan code — pcd_stan_path","text":"","code":"pcd_stan_path()"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pcd_stan_path.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get the path to the Stan code — pcd_stan_path","text":"character string path Stan code","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute the primary event censored CDF for delays — pprimarycensoreddist","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"function computes primary event censored cumulative distribution function (CDF) given set quantiles. adjusts CDF primary event distribution accounting delay distribution potential truncation maximum delay (D). function allows custom primary event distributions delay distributions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"","code":"pprimarycensoreddist( q, pdist, pwindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), ... ) ppcens( q, pdist, pwindow = 1, D = Inf, dprimary = stats::dunif, dprimary_args = list(), ... )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"q Vector quantiles pdist Distribution function (CDF) pwindow Primary event window D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. dprimary Function generate probability density function (PDF) primary event times. function take value x pwindow parameter, return probability density. normalized integrate 1 [0, pwindow]. Defaults uniform distribution [0, pwindow]. Users can provide custom functions use helper functions like dexpgrowth exponential growth distribution. See primary_dists.R examples. dprimary_args List additional arguments passed dprimary. example, using dexpgrowth, pass list(min = 0, max = pwindow, r = 0.2) set minimum, maximum, rate parameters. ... Additional arguments passed pdist","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"Vector primary event censored CDFs, normalized D finite (truncation adjustment)","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"primary event censored CDF computed integrating product primary event distribution function (CDF) delay distribution function (PDF) primary event window. integration adjusted truncation finite maximum delay (D) specified. primary event censored CDF, \\(F_{\\text{cens}}(q)\\), given : $$ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} F(q - p) \\cdot f_{\\text{primary}}(p) \\, dp $$ \\(F\\) CDF primary event distribution, \\(f_{\\text{primary}}\\) PDF primary event times, \\(pwindow\\) primary event window. maximum delay \\(D\\) finite, CDF normalized \\(F(D)\\): $$ F_{\\text{cens}}(q) = \\int_{0}^{pwindow} \\frac{F(q - p)}{F(D - p)} \\cdot f_{\\text{primary}}(p) \\, dp $$","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/pprimarycensoreddist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute the primary event censored CDF for delays — pprimarycensoreddist","text":"","code":"# Example: Lognormal distribution with uniform primary events pprimarycensoreddist(c(0.1, 0.5, 1), plnorm, meanlog = 0, sdlog = 1) #> [1] 0.0002753181 0.0475094631 0.2384217081 # Example: Lognormal distribution with exponential growth primary events pprimarycensoreddist( c(0.1, 0.5, 1), plnorm, dprimary = dexpgrowth, dprimary_args = list(r = 0.2), meanlog = 0, sdlog = 1 ) #> [1] 0.0002496934 0.0440815583 0.2290795695"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"function generates random samples primary event censored distribution. adjusts distribution accounting primary event distribution potential truncation maximum delay (D). function allows custom primary event distributions delay distributions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"","code":"rprimarycensoreddist( n, rdist, pwindow = 1, swindow = 1, D = Inf, rprimary = stats::runif, rprimary_args = list(), oversampling_factor = 1.2, ... ) rpcens( n, rdist, pwindow = 1, swindow = 1, D = Inf, rprimary = stats::runif, rprimary_args = list(), oversampling_factor = 1.2, ... )"},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"n Number random samples generate. rdist Function generate random samples delay distribution example stats::rlnorm() lognormal distribution. pwindow Primary event window swindow Integer specifying window size rounding delay (default 1). swindow = 0 rounding applied. D Maximum delay (truncation point). finite, distribution truncated D. set Inf, truncation applied. Defaults Inf. rprimary Function generate random samples primary distribution (default stats::runif()). rprimary_args List additional arguments passed rprimary. oversampling_factor Factor oversample number samples account truncation (default 1.2). ... Additional arguments passed distribution function.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"Vector random samples primary event censored distribution censored secondary event window.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"mathematical formulation generating random samples primary event censored distribution follows: Generate primary event times (p) specified primary event distribution (f_p) within primary event window (pwindow): $$p \\sim f_p(x), \\quad 0 \\leq x \\leq pwindow$$ Generate delays (d) specified delay distribution (f_d) parameters theta: $$d \\sim f_d(x; \\theta)$$ Calculate total delays (t) adding primary event times delays: $$t = p + d$$ Apply truncation ensure delays within specified range [0, D]: $$t_{truncated} = \\{t \\mid 0 \\leq t < D\\}$$ Round truncated delays nearest secondary event window (swindow): $$t_{valid} = \\lfloor \\frac{t_{truncated}}{swindow} \\rfloor \\times swindow$$ function oversamples account potential truncation generates additional samples needed reach desired number valid samples.","code":""},{"path":[]},{"path":"https://primarycensoreddist.epinowcast.org/dev/reference/rprimarycensoreddist.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate random samples from a primary event censored distribution — rprimarycensoreddist","text":"","code":"# Example: Lognormal distribution with uniform primary events rprimarycensoreddist(10, rlnorm, meanlog = 0, sdlog = 1) #> [1] 1 3 3 1 1 6 1 3 4 1 # Example: Lognormal distribution with exponential growth primary events rprimarycensoreddist( 10, rlnorm, rprimary = rexpgrowth, rprimary_args = list(r = 0.2), meanlog = 0, sdlog = 1 ) #> [1] 1 3 1 0 1 1 2 9 1 1"},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"primarycensoreddist-0201000","dir":"Changelog","previous_headings":"","what":"primarycensoreddist 0.2.0.1000","title":"primarycensoreddist 0.2.0.1000","text":"Development version.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"primarycensoreddist-020","dir":"Changelog","previous_headings":"","what":"primarycensoreddist 0.2.0","title":"primarycensoreddist 0.2.0","text":"release puts place initial documentation vignettes. also includes new primary censored distribution interface allow non-secondary event censored distributions. Development release identified numerical issues gradient evaluations primary censored distributions may lead breaking interface changes 0.3.0 Stan code.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"package-0-2-0","dir":"Changelog","previous_headings":"","what":"Package","title":"primarycensoreddist 0.2.0","text":"Added support swindow = 0 rprimarycensoreddist allow non-secondary event censored distributions. Adapted rprimarycensoreddist truncation based primary censored distribution secondary events censored. better matches generative process. Added new Stan interface tool enable finding files functions implemented Stan code.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"documentation-0-2-0","dir":"Changelog","previous_headings":"","what":"Documentation","title":"primarycensoreddist 0.2.0","text":"Added getting started vignette. Added vignette showcasing use package Stan code cmdstanr. Added vignette showcasing fit distributions using cmdstanr package.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"primarycensoreddist-010","dir":"Changelog","previous_headings":"","what":"primarycensoreddist 0.1.0","title":"primarycensoreddist 0.1.0","text":"initial primarycensoreddist release includes R stan tools dealing potentially truncated primary event censored delay distributions. expect current features work UI may change package matures next versions.","code":""},{"path":"https://primarycensoreddist.epinowcast.org/dev/news/index.html","id":"package-0-1-0","dir":"Changelog","previous_headings":"","what":"Package","title":"primarycensoreddist 0.1.0","text":"Added package skeleton. Added checking input functions. Added stan functions primary censored truncated distributions. Added R functions primary censored truncated distributions. Add R function facilitate working Stan code. Added tests primary censored truncated distributions. Added tests compare R Stan implementations. Added tests R functions facilitate working Stan code. Resolved R CMD check errors, warnings notes. Added hexsticker. Added vignette skeletons preparation 0.2.0 release.","code":""}]
Under construction
In this vignette, we’ll demonstrate how to use primarycensoreddist in conjunction with Stan for Bayesian inference of epidemiological delay distributions. We’ll cover the following key points:
primarycensoreddist
This vignette builds on the concepts introduced in the Getting Started with primarycensoreddist vignette and assumes familiarity with using Stan tools as covered in the How to use primarycensoreddist with Stan vignette.
Alongside the primarycensoreddist package we will use the cmdstanr package for interfacing with cmdstan. We will also use the ggplot2 package for plotting and dplyr for data manipulation.
cmdstanr
ggplot2
dplyr
+library(primarycensoreddist) +library(cmdstanr) +library(ggplot2) +library(dplyr)
library(primarycensoreddist) +library(cmdstanr) +library(ggplot2) +library(dplyr)
We’ll start by simulating some censored and truncated delay distribution data. We’ll use the rprimarycensoreddist function (actually we will use the rpcens alias for brevity).
rprimarycensoreddist
rpcens
+set.seed(123) # For reproducibility + +# Define the true distribution parameters +n <- 1000 +meanlog <- 1.5 +sdlog <- 0.75 + +# Generate varying pwindow, swindow, and obs_time lengths +pwindows <- sample(1, n, replace = TRUE) +swindows <- sample(1, n, replace = TRUE) +obs_times <- 10 + +# Function to generate a single sample +generate_sample <- function(pwindow, swindow, obs_time) { + rpcens( + 1, rlnorm, + meanlog = meanlog, sdlog = sdlog, + pwindow = pwindow, swindow = swindow, D = obs_time + ) +} + +# Generate samples +samples <- mapply(generate_sample, pwindows, swindows, obs_times) + +# Create initial data frame +delay_data <- data.frame( + pwindow = pwindows, + swindow = swindows, + obs_time = obs_times, + observed_delay = samples +) + +head(delay_data)
set.seed(123) # For reproducibility + +# Define the true distribution parameters +n <- 1000 +meanlog <- 1.5 +sdlog <- 0.75 + +# Generate varying pwindow, swindow, and obs_time lengths +pwindows <- sample(1, n, replace = TRUE) +swindows <- sample(1, n, replace = TRUE) +obs_times <- 10 + +# Function to generate a single sample +generate_sample <- function(pwindow, swindow, obs_time) { + rpcens( + 1, rlnorm, + meanlog = meanlog, sdlog = sdlog, + pwindow = pwindow, swindow = swindow, D = obs_time + ) +} + +# Generate samples +samples <- mapply(generate_sample, pwindows, swindows, obs_times) + +# Create initial data frame +delay_data <- data.frame( + pwindow = pwindows, + swindow = swindows, + obs_time = obs_times, + observed_delay = samples +) + +head(delay_data)
## pwindow swindow obs_time observed_delay +## 1 1 1 10 2 +## 2 1 1 10 1 +## 3 1 1 10 8 +## 4 1 1 10 6 +## 5 1 1 10 5 +## 6 1 1 10 4
+# Aggregate to unique combinations and count occurrences +# Aggregate to unique combinations and count occurrences +delay_counts <- delay_data |> + summarise(n = n(), .by = c(pwindow, swindow, obs_time, observed_delay)) + +head(delay_counts)
# Aggregate to unique combinations and count occurrences +# Aggregate to unique combinations and count occurrences +delay_counts <- delay_data |> + summarise(n = n(), .by = c(pwindow, swindow, obs_time, observed_delay)) + +head(delay_counts)
## pwindow swindow obs_time observed_delay n +## 1 1 1 10 2 160 +## 2 1 1 10 1 96 +## 3 1 1 10 8 59 +## 4 1 1 10 6 113 +## 5 1 1 10 5 119 +## 6 1 1 10 4 150
+# Compare the samples with and without secondary censoring to the true +# distribution +# Calculate empirical CDF +empirical_cdf <- ecdf(samples) + +# Create a sequence of x values for the theoretical CDF +x_seq <- seq(min(samples), max(samples), length.out = 100) + +# Calculate theoretical CDF +theoretical_cdf <- plnorm(x_seq, meanlog = meanlog, sdlog = sdlog) + +# Create a long format data frame for plotting +cdf_data <- data.frame( + x = rep(x_seq, 2), + probability = c(empirical_cdf(x_seq), theoretical_cdf), + type = rep(c("Observed", "Theoretical"), each = length(x_seq)), + stringsAsFactors = FALSE +) + +# Plot +ggplot(cdf_data, aes(x = x, y = probability, color = type)) + + geom_step(linewidth = 1) + + scale_color_manual( + values = c(Observed = "#4292C6", Theoretical = "#252525") + ) + + geom_vline( + aes(xintercept = mean(samples), color = "Observed"), + linetype = "dashed", linewidth = 1 + ) + + geom_vline( + aes(xintercept = exp(meanlog + sdlog^2 / 2), color = "Theoretical"), + linetype = "dashed", linewidth = 1 + ) + + labs( + title = "Comparison of Observed vs Theoretical CDF", + x = "Delay", + y = "Cumulative Probability", + color = "CDF Type" + ) + + theme_minimal() + + theme( + panel.grid.minor = element_blank(), + plot.title = element_text(hjust = 0.5), + legend.position = "bottom" + )
# Compare the samples with and without secondary censoring to the true +# distribution +# Calculate empirical CDF +empirical_cdf <- ecdf(samples) + +# Create a sequence of x values for the theoretical CDF +x_seq <- seq(min(samples), max(samples), length.out = 100) + +# Calculate theoretical CDF +theoretical_cdf <- plnorm(x_seq, meanlog = meanlog, sdlog = sdlog) + +# Create a long format data frame for plotting +cdf_data <- data.frame( + x = rep(x_seq, 2), + probability = c(empirical_cdf(x_seq), theoretical_cdf), + type = rep(c("Observed", "Theoretical"), each = length(x_seq)), + stringsAsFactors = FALSE +) + +# Plot +ggplot(cdf_data, aes(x = x, y = probability, color = type)) + + geom_step(linewidth = 1) + + scale_color_manual( + values = c(Observed = "#4292C6", Theoretical = "#252525") + ) + + geom_vline( + aes(xintercept = mean(samples), color = "Observed"), + linetype = "dashed", linewidth = 1 + ) + + geom_vline( + aes(xintercept = exp(meanlog + sdlog^2 / 2), color = "Theoretical"), + linetype = "dashed", linewidth = 1 + ) + + labs( + title = "Comparison of Observed vs Theoretical CDF", + x = "Delay", + y = "Cumulative Probability", + color = "CDF Type" + ) + + theme_minimal() + + theme( + panel.grid.minor = element_blank(), + plot.title = element_text(hjust = 0.5), + legend.position = "bottom" + )
We’ve aggregated the data to unique combinations of pwindow, swindow, and obs_time and counted the number of occurrences of each observed_delay for each combination. This is the data we will use to fit our model.
pwindow
swindow
obs_time
observed_delay
We’ll start by fitting a naive model using cmdstan. We’ll use the cmdstanr package to interface with cmdstan. We define the model in a string and then write it to a file as in the How to use primarycensoreddist with Stan vignette.
+writeLines( + "data { + int<lower=0> N; // number of observations + vector[N] y; // observed delays + vector[N] n; // number of occurrences for each delay + } + parameters { + real mu; + real<lower=0> sigma; + } + model { + // Priors + mu ~ normal(1, 1); + sigma ~ normal(0.5, 1); + + // Likelihood + target += n .* lognormal_lpdf(y | mu, sigma); + }", + con = file.path(tempdir(), "naive_lognormal.stan") +)
writeLines( + "data { + int<lower=0> N; // number of observations + vector[N] y; // observed delays + vector[N] n; // number of occurrences for each delay + } + parameters { + real mu; + real<lower=0> sigma; + } + model { + // Priors + mu ~ normal(1, 1); + sigma ~ normal(0.5, 1); + + // Likelihood + target += n .* lognormal_lpdf(y | mu, sigma); + }", + con = file.path(tempdir(), "naive_lognormal.stan") +)
Now let’s compile the model
+naive_model <- cmdstan_model(file.path(tempdir(), "naive_lognormal.stan"))
naive_model <- cmdstan_model(file.path(tempdir(), "naive_lognormal.stan"))
and now let’s fit the compiled model.
+naive_fit <- naive_model$sample( + data = list( + # Add a small constant to avoid log(0) + y = delay_counts$observed_delay + 1e-6, + n = delay_counts$n, + N = nrow(delay_counts) + ), + chains = 4, + parallel_chains = 4, + show_messages = FALSE, + refresh = 0 +) +naive_fit
naive_fit <- naive_model$sample( + data = list( + # Add a small constant to avoid log(0) + y = delay_counts$observed_delay + 1e-6, + n = delay_counts$n, + N = nrow(delay_counts) + ), + chains = 4, + parallel_chains = 4, + show_messages = FALSE, + refresh = 0 +) +naive_fit
## Warning: NAs introduced by coercion
## variable mean median sd mad q5 q95 rhat ess_bulk +## lp__ -28480.45 -28480.10 1.00 0.74 -28482.40 -28479.50 1.00 1999 +## mu -0.10 -0.10 0.05 0.04 -0.18 -0.02 1.00 2691 +## sigma 4.61 4.61 0.03 0.03 4.56 4.67 1.00 3820 +## ess_tail +## NA +## 2310 +## 2869
We see that the model has converged and the diagnostics look good. However, just from the model posterior summary we see that we might not be very happy with the fit. mu is smaller than the target 1.5 and sigma is larger than the target 0.75.
mu
sigma
We’ll now fit an improved model using the primarycensoreddist package. The main improvement is that we will use the primary_censored_dist_lpdf function to fit the model. This is the Stan version of the pcens() function and accounts for the primary and secondary censoring windows as well as the truncation. We encode that our primary distribution is a lognormal distribution by passing 1 as the dist_id parameter and that our primary event distribution is uniform by passing 1 as the primary_dist_id parameter. See the Stan documentation for more details on the primary_censored_dist_lpdf function.
primary_censored_dist_lpdf
pcens()
dist_id
primary_dist_id
+writeLines( + " + functions { + #include primary_censored_dist.stan + #include expgrowth.stan + } + data { + int<lower=0> N; // number of observations + array[N] int<lower=0> y; // observed delays + array[N] int<lower=0> n; // number of occurrences for each delay + array[N] int<lower=0> pwindow; // primary censoring window + array[N] int<lower=0> swindow; // secondary censoring window + array[N] int<lower=0> D; // maximum delay + } + transformed data { + array[0] real primary_params; + } + parameters { + real mu; + real<lower=0> sigma; + } + model { + // Priors + mu ~ normal(1, 1); + sigma ~ normal(0.5, 0.5); + + // Likelihood + for (i in 1:N) { + target += n[i] * primary_censored_dist_lpmf( + y[i] | 1, {mu, sigma}, + pwindow[i], swindow[i], D[i], + 1, primary_params + ); + } + }", + con = file.path(tempdir(), "primarycensoreddist_lognormal.stan") +)
writeLines( + " + functions { + #include primary_censored_dist.stan + #include expgrowth.stan + } + data { + int<lower=0> N; // number of observations + array[N] int<lower=0> y; // observed delays + array[N] int<lower=0> n; // number of occurrences for each delay + array[N] int<lower=0> pwindow; // primary censoring window + array[N] int<lower=0> swindow; // secondary censoring window + array[N] int<lower=0> D; // maximum delay + } + transformed data { + array[0] real primary_params; + } + parameters { + real mu; + real<lower=0> sigma; + } + model { + // Priors + mu ~ normal(1, 1); + sigma ~ normal(0.5, 0.5); + + // Likelihood + for (i in 1:N) { + target += n[i] * primary_censored_dist_lpmf( + y[i] | 1, {mu, sigma}, + pwindow[i], swindow[i], D[i], + 1, primary_params + ); + } + }", + con = file.path(tempdir(), "primarycensoreddist_lognormal.stan") +)
+primarycensoreddist_model <- cmdstan_model( + file.path(tempdir(), "primarycensoreddist_lognormal.stan"), + include_paths = pcd_stan_path() +)
primarycensoreddist_model <- cmdstan_model( + file.path(tempdir(), "primarycensoreddist_lognormal.stan"), + include_paths = pcd_stan_path() +)
Now let’s fit the compiled model.
+primarycensoreddist_fit <- primarycensoreddist_model$sample( + data = list( + y = delay_counts$observed_delay, + n = delay_counts$n, + pwindow = delay_counts$pwindow, + swindow = delay_counts$swindow, + D = delay_counts$obs_time, + N = nrow(delay_counts) + ), + chains = 4, + parallel_chains = 4, + init = list( # we use this to resolve initialisation issues + list(mu = 1.5, sigma = 0.6), + list(mu = 1.5, sigma = 0.4), + list(mu = 1.5, sigma = 0.3), + list(mu = 1.5, sigma = 0.55) + ), + refresh = 0, + show_messages = FALSE +) +primarycensoreddist_fit
primarycensoreddist_fit <- primarycensoreddist_model$sample( + data = list( + y = delay_counts$observed_delay, + n = delay_counts$n, + pwindow = delay_counts$pwindow, + swindow = delay_counts$swindow, + D = delay_counts$obs_time, + N = nrow(delay_counts) + ), + chains = 4, + parallel_chains = 4, + init = list( # we use this to resolve initialisation issues + list(mu = 1.5, sigma = 0.6), + list(mu = 1.5, sigma = 0.4), + list(mu = 1.5, sigma = 0.3), + list(mu = 1.5, sigma = 0.55) + ), + refresh = 0, + show_messages = FALSE +) +primarycensoreddist_fit
## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail +## lp__ -2134.42 -2134.13 0.97 0.70 -2136.43 -2133.49 1.00 732 952 +## mu 1.53 1.53 0.05 0.05 1.46 1.61 1.01 620 686 +## sigma 0.77 0.77 0.04 0.04 0.71 0.83 1.00 633 641
We see that the model has converged and the diagnostics look good. We also see that the posterior means are very near the true parameters and the 90% credible intervals include the true parameters.
Stan is a probabilistic programming language for statistical inference. It provides a flexible and efficient platform for Bayesian modeling and is widely used in various fields of data science and statistics. In this vignette, we’ll use Stan in conjunction with primarycensoreddist to perform Bayesian inference on censored data.
For more information on Stan: -- Stan’s official website -- Stan documentation -- Stan forums for community support and discussions
For more information on Stan:
Stan functions are accessed using the pcd_load_stan_functions() function. This function takes the name of the function as an argument and returns the function as a string. It can additionally write the functions to a file and wrap them in a functions{} block.
pcd_load_stan_functions()
functions{}
pcd_load_stan_functions("primary_censored_dist_lpmf")
## [1] "// Stan functions from primarycensoreddist version 0.1.0.1000\nreal primary_censored_dist_lpmf(int d, int dist_id, array[] real params,\n data real pwindow, real swindow, data real D,\n int primary_dist_id, array[] real primary_params) {\n\n real d_upper = d + swindow;\n if (d_upper > D) {\n reject(\"Upper truncation point is greater than D. It is \", d_upper,\n \" and D is \", D, \". Resolve this by increasing D to be greater or equal to d + swindow.\");\n }\n real log_cdf_upper = primary_censored_dist_lcdf(\n d_upper | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n real log_cdf_lower = primary_censored_dist_lcdf(\n d | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n return log_diff_exp(log_cdf_upper, log_cdf_lower);\n}"
## [1] "// Stan functions from primarycensoreddist version 0.2.0.1000\nreal primary_censored_dist_lpmf(int d, int dist_id, array[] real params,\n data real pwindow, real swindow, data real D,\n int primary_dist_id, array[] real primary_params) {\n\n real d_upper = d + swindow;\n if (d_upper > D) {\n reject(\"Upper truncation point is greater than D. It is \", d_upper,\n \" and D is \", D, \". Resolve this by increasing D to be greater or equal to d + swindow.\");\n }\n real log_cdf_upper = primary_censored_dist_lcdf(\n d_upper | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n real log_cdf_lower = primary_censored_dist_lcdf(\n d | dist_id, params, pwindow, D, primary_dist_id, primary_params\n );\n return log_diff_exp(log_cdf_upper, log_cdf_lower);\n}"
## Stan functions written to: /tmp/RtmpaPRJO3/expgrowth_rng.stan
## Stan functions written to: /tmp/RtmpaPzbyH/expgrowth_rng.stan
This can now be compiled and used in the same way as any other cmdstanr model.
model <- cmdstan_model(expgrowth_rng_file) model
## functions { -## // Stan functions from primarycensoreddist version 0.1.0.1000 +## // Stan functions from primarycensoreddist version 0.2.0.1000 ## real expgrowth_rng(real min, real max, real r) { ## real u = uniform_rng(0, 1); ## if (abs(r) < 1e-10) { @@ -203,20 +206,44 @@ text = c( "functions {", "#include expgrowth.stan", + "}", + "generated quantities {", + " real y = expgrowth_rng(0, 1, 0.4);", "}" ), con = expgrowth_stan_file )
}
We can now use this file to compile a model. **Note** that we need to include the path to the `primarycensoreddist` Stan functions using the `include_paths` argument to `cmdstan_model()`. - - -``` r -model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) -model
We can now use this file to compile a model. Note that we need to include the path to the primarycensoreddist Stan functions using the include_paths argument to cmdstan_model().
include_paths
cmdstan_model()
+model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) +model
model <- cmdstan_model(expgrowth_stan_file, include_paths = pcd_stan_path()) +model
## functions { ## #include expgrowth.stan +## } +## generated quantities { +## real y = expgrowth_rng(0, 1, 0.4); ## }
We can then sample from the model (we set fixed_param = TRUE here as our toy example doesn’t require MCMC sampling).
fixed_param = TRUE
+samples <- model$sample(chains = 1, fixed_param = TRUE)
samples <- model$sample(chains = 1, fixed_param = TRUE)
## Running MCMC with 1 chain... +## +## Chain 1 Iteration: 1 / 1000 [ 0%] (Sampling) +## Chain 1 Iteration: 100 / 1000 [ 10%] (Sampling) +## Chain 1 Iteration: 200 / 1000 [ 20%] (Sampling) +## Chain 1 Iteration: 300 / 1000 [ 30%] (Sampling) +## Chain 1 Iteration: 400 / 1000 [ 40%] (Sampling) +## Chain 1 Iteration: 500 / 1000 [ 50%] (Sampling) +## Chain 1 Iteration: 600 / 1000 [ 60%] (Sampling) +## Chain 1 Iteration: 700 / 1000 [ 70%] (Sampling) +## Chain 1 Iteration: 800 / 1000 [ 80%] (Sampling) +## Chain 1 Iteration: 900 / 1000 [ 90%] (Sampling) +## Chain 1 Iteration: 1000 / 1000 [100%] (Sampling) +## Chain 1 finished in 0.0 seconds.
+samples
samples
## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail +## y 0.51 0.52 0.29 0.38 0.06 0.95 1.00 1065 983
Whilst it is possible to use Stan functions directly in R it is not recommended for most use cases (use the R functions in primarycensoreddist instead). However, it can be useful to understand what is going on under the hood or for exploration (indeed we use this internally in primarycensoreddist to check our functions against the R implementations). To do this we use the expose_functions() method on our already compiled model.
expose_functions()
+ model$expose_functions(global = TRUE) -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_nvecserial.a -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_cvodes.a -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_idas.a -## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_kinsol.a -## /home/runner/.cmdstan/cmdstan-2.35.0/stan/lib/stan_math/lib/tbb_2020.3/build/Makefile.tbb:28: CONFIG: cfg=release arch=intel64 compiler=gcc target=linux runtime=cc11.4.0_libc2.35_kernel6.5.0 We can now use the function in R. Note that this may get slightly more complicated if our stan function depends on other stan functions (i.e. you need to have those included in your compiled model as well). - + expgrowth_rng(0, 1, 0.4) -## [1] 0.5643954 +## [1] 0.6524848
model$expose_functions(global = TRUE)
## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_nvecserial.a
## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_cvodes.a
## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_idas.a
## ar: creating stan/lib/stan_math/lib/sundials_6.1.1/lib/libsundials_kinsol.a
## /home/runner/.cmdstan/cmdstan-2.35.0/stan/lib/stan_math/lib/tbb_2020.3/build/Makefile.tbb:28: CONFIG: cfg=release arch=intel64 compiler=gcc target=linux runtime=cc11.4.0_libc2.35_kernel6.5.0
We can now use the function in R. Note that this may get slightly more complicated if our stan function depends on other stan functions (i.e. you need to have those included in your compiled model as well).
+ expgrowth_rng(0, 1, 0.4) -## [1] 0.5643954 +## [1] 0.6524848
expgrowth_rng(0, 1, 0.4)
## [1] 0.5643954
## [1] 0.6524848
Development version.
This release puts in place initial documentation and vignettes. It also includes a new primary censored distribution interface to allow for non-secondary event censored distributions. Development of this release as identified some numerical issues in the gradient evaluations for the primary censored distributions which may lead to breaking interface changes in 0.3.0 for the Stan code.
0.3.0
swindow = 0