Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert simulation code to use exact numbers rather than approximation #329

Open
gowerc opened this issue May 21, 2024 · 0 comments
Open
Labels
enhancement New feature or request Needs Review

Comments

@gowerc
Copy link
Collaborator

gowerc commented May 21, 2024

The current simulation code essentially performs a rough integration by manually calculating the trapeziums with a user defined spacing between each rectangle. Whilst this works its not that performant and is confusing to explain to end users as they have to define the step size which is something they shouldn't have to worry about. Would be ideal to replace this with using R's numeric integration functions instead. A rough working example of this can be seen below which implements a random sampler for the Weibull distribution:

hazard_fun <- function(t) {
    lambda <- 1 / 200
    gamma <- 0.95
    lambda * gamma * t^(gamma - 1)
}

loss_fun <- function(x, u) {
    survival_prob <- exp(-integrate(hazard_fun, lower = 0, upper = x)$value)
    abs(u - survival_prob)
}

rwei <- function(n) {
    vapply(
        runif(6000),
        \(u) optimise(loss_fun, c(0, 10000), u = u)$minimum,
        numeric(1)
    )
}


## Compare against flexsurv to show that its working
flexsurv::rweibullPH(6000, scale = 1 / 200, shape = 0.95) |>
    density() |>
    plot(col = "red")

rwei(6000) |>
    density() |>
    lines(col = "black")
@gowerc gowerc added the enhancement New feature or request label May 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request Needs Review
Projects
None yet
Development

No branches or pull requests

1 participant