Skip to content

Instantly share code, notes, and snippets.

@kylebaron
Last active March 4, 2016 19:17
Show Gist options
  • Save kylebaron/4b5b7d970b6f042d07c9 to your computer and use it in GitHub Desktop.
Save kylebaron/4b5b7d970b6f042d07c9 to your computer and use it in GitHub Desktop.
Set RNGkind in worker
library(shiny)
library(mrgsolve)
library(dplyr)
library(magrittr)
library(parallel)
RNGkind("L'Ecuyer-CMRG")
set.seed(101)
mc.reset.stream()
##' A model to simulate ETAs
code <- '
$OMEGA 0 0
$TABLE
table(ETA1) = ETA(1);
table(ETA2) = ETA(2);
'
mod <- mread("shinymc",tempdir(),code,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),
sliderInput("seed", "set.seed",1,50,25,1)
),
mainPanel(tableOutput("table")
)
)
)
##' Simulate
##' The KEY is to set the RNGkind on the worker
sim <- function(i,x,idata) {
RNGkind("L'Ecuyer-CMRG")
x %>% idata_set(idata) %>% mrgsim(end=-1) %>% 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) {
##' For now, be safe
RNGkind("L'Ecuyer-CMRG")
output$table <- renderTable({
idata <- data_frame(ID=1:input$N)
mod %<>% omat(dmat(input$OM1,input$OM2))
##' For now, be safe
RNGkind("L'Ecuyer-CMRG")
set.seed(as.integer(input$seed))
mc.reset.stream()
mclapply(1:input$n,
mc.cores=input$mccores,
sim,
mod,
idata) %>% 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