Skip to content

Instantly share code, notes, and snippets.

@slwu89
Created March 16, 2023 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slwu89/d5a55e9d37c326e4bd489d684f7c9512 to your computer and use it in GitHub Desktop.
Save slwu89/d5a55e9d37c326e4bd489d684f7c9512 to your computer and use it in GitHub Desktop.
piecewise exp firing time sampling
rpwexp <- function(n, failRates) {
end_time <- cumsum(failRates$duration)
n_rate <- nrow(failRates)
t <- 0
tau <- Tk <- rep(0, n)
Pk <- rexp(n = n)
notfired <- rep(TRUE, n)
for (i in 1:n_rate) {
delta_tk <- (Pk[notfired] - Tk[notfired]) / failRates$rate[i]
tau[notfired] <- t + delta_tk
if (i < n_rate) {
notfired[notfired] <- tau[notfired] >= end_time[i]
t <- t + failRates$duration[i]
Tk <- Tk + failRates$rate[i]*failRates$duration[i]
}
if (!any(notfired)) {
break
}
}
return(tau)
}
failRates <- data.frame(rate = c(1, 3, 0.5, 0.1, 2, 1.5, 0.1, 0.9), duration = c(.5, .5, 1, 0.25, 0.5, 1, 2, 1))
x <- rpwexp(n = 1e4, failRates = failRates)
plot(sort(x), (1e4:1)/10001,
log = "y", main = "PW Exponential simulated survival curve",
xlab = "Time", ylab = "P{Survival}", col = adjustcolor("red",alpha.f = 0.15), pch = 16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment