Skip to content

Instantly share code, notes, and snippets.

@kylebaron
Last active February 26, 2016 05:32
Show Gist options
  • Save kylebaron/d9fca29f3951c145db82 to your computer and use it in GitHub Desktop.
Save kylebaron/d9fca29f3951c145db82 to your computer and use it in GitHub Desktop.
Problems with RNG when using mclapply inside shiny app
library(shiny)
library(mrgsolve)
library(dplyr)
library(magrittr)
library(parallel)
RNGkind("L'Ecuyer-CMRG")
set.seed(101)
mc.reset.stream()
code <- '
$OMEGA 0 0
$TABLE
table(ETA1) = ETA(1);
table(ETA2) = ETA(2);
'
mod <- mread(code=code, "shinymc", tempdir(),warn=FALSE)
##' UI ###########################################
ui<- fluidPage(
titlePanel("Shiny MC"),
sidebarLayout(
sidebarPanel(
sliderInput("OM1", "OMEGA 1",0,4,1,0.25),
sliderInput("OM2", "OMEGA 2",0,4,1,.25),
sliderInput("n", "N rep", 1,100,10,1),
sliderInput("N", "N subj", 1, 100,10,1),
sliderInput("mccores", "mc.cores", 1,4,2,1),
checkboxInput("fix", "Implement workaround",FALSE)
),
mainPanel(tableOutput("table")
)
)
)
##' Simulate
##' if(fix) the seed will be set based on replicate number
sim <- function(i,x,idata,fix) {
if(fix) set.seed(as.integer(paste0(1232,i)))
x %>% idata_set(idata) %>% mrgsim(end=-1) %>% as.tbl %>% mutate(irep=i)
}
##' Summarize simulations
smry <- function(x) {
x %>% summarise(nETA1 = n_distinct(ETA1),
vETA1 = var(ETA1),
sETA1 = sum(ETA1),
nETA2 = n_distinct(ETA2),
vETA2 = var(ETA2),
sETA2 = sum(ETA2),
n=n())
}
##' SERVER ###########################################
server<-function(input, output) {
output$table <- renderTable({
idata <- data_frame(ID=1:input$N)
mod %<>% omat(dmat(input$OM1,input$OM2))
fix <- input$fix
mclapply(1:input$n,
mc.cores=input$mccores,
sim,
mod,
idata,
fix) %>% bind_rows %>% smry
})
}
##' Run the shiny app
shinyApp(ui = ui, server = server)
##' Run the shiny app simulation outside of shiny
RNGkind("L'Ecuyer-CMRG")
set.seed(101)
mc.reset.stream()
out <- mclapply(1:10,mc.cores=4,sim,
mod %>% omat(dmat(1,1)),
data_frame(ID=1:100),FALSE) %>% bind_rows
out %>% smry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment