Skip to content

Instantly share code, notes, and snippets.

@SachaEpskamp
Last active December 17, 2015 21:49
Show Gist options
  • Save SachaEpskamp/5677320 to your computer and use it in GitHub Desktop.
Save SachaEpskamp/5677320 to your computer and use it in GitHub Desktop.
Ising example
library("qgraph")
library("igraph")
library("Rcpp")
library("shiny")
download.file("http://sachaem47.fortyseven.versio.nl/files/IsingCppBinary.cpp", file <- tempfile(fileext=".cpp"))
sourceCpp(file)
shinyServer(function(input, output) {
# Network parameters:
J <- reactive({
network <- matrix(input$net,input$nNodes,input$nNodes)
diag(network) <- 0
return(network)
})
h <- reactive({
return(rep(input$thresh, input$nNodes))
})
AllStates <- reactive({
return(do.call(expand.grid,lapply(1:input$nNodes,function(x)c(0L,1L))))
})
output$adjplot <- renderPlot({
qgraph(J(),weighted=FALSE)
})
### State distribution:
output$statedist <- renderTable({
Dist <- exp(-input$beta * apply(AllStates(),1,function(s)H(J(),s,h())))
Dist <- Dist/sum(Dist)
### Return:
return(cbind(AllStates(), P = Dist))
})
### State distribution:
output$endist <- renderPlot({
En <- apply(AllStates(),1,function(s)H(J(),s,h()))
layout(1:2)
curve(exp(-input$beta * x), min(En), max(En), yaxt = "n", xlab = "Energy", ylab = "Probability", bty = "n")
hist(En, breaks = 16, xlim=c( min(En), max(En)), xlab = "Energy", ylab = "Number of states", main = "")
})
# Sumscore distribution:
output$sumdist <- renderPlot({
Dist <- IsingDirLik(Graph = J(), Thresholds = h(), Beta = input$beta)
barplot(Dist$P, names.arg = Dist$Sum)
},width='auto',height='auto')
# Plotting window:
output$window <- renderUI({
if (input$show == 'Sumscore distribution')
{
plotOutput('sumdist', width = 1000, height = 500)
} else if (input$show == 'State distribution')
{
tableOutput('statedist')
} else
{
plotOutput('endist', width = 1000, height = 1000)
}
})
})
shinyUI(pageWithSidebar(
# Header:
headerPanel("Ising example (fully connected network)"),
# Input in sidepanel:
sidebarPanel(
sliderInput("nNodes", "Number of Nodes:",
min=1, max=10, value=2, step = 1),
sliderInput("net", "Network Strength:",
min=0, max=10, value=1, step = 0.1),
sliderInput("thresh", "External Field:",
min=-10, max=0, value=-1, step = 0.1),
sliderInput("beta", "Inverse Temperature:",
min=0.1, max=5, value=1, step = 0.1),
br(),
plotOutput("adjplot",'100%')
),
# Plot in main:
mainPanel(
# Show a plot of the generated distribution
radioButtons("show", "Show:",
c('Sumscore distribution','State distribution','Energy distribution')),
htmlOutput("window")
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment