Skip to content

Instantly share code, notes, and snippets.

@caboulton
Last active December 23, 2015 10:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save caboulton/211560effed7e986d7bd to your computer and use it in GitHub Desktop.
Save caboulton/211560effed7e986d7bd to your computer and use it in GitHub Desktop.
Early warning signals shiny program for use in R
library(shiny)
library(Kendall)
shinyServer(function(input, output) {
output$tsplot <- renderPlot({
table <- read.table('tip.txt')
ts <- table[,1]
tscut <- ts[1:input$cut]
smoothed <- ksmooth(c(1:input$cut),tscut,bandwidth=input$bw,x.points=c(1:input$cut))
detrend <- tscut - smoothed$y
plot(ts,type="l",ylab='X')
lines(smoothed,col='red')
lines(c(input$cut,input$cut),c(-100,100),lty=3)
})
output$ar1plot <- renderPlot({
table <- read.table('tip.txt')
ts <- table[,1]
tscut <- ts[1:input$cut]
smoothed <- ksmooth(c(1:input$cut),tscut,bandwidth=input$bw,x.points=c(1:input$cut))
detrend <- tscut - smoothed$y
ar1 <- rep(NA, (length(ts)-input$wl))
for (i in 1:(input$cut-input$wl)) {
arfit <- ar.ols(detrend[i:(i+input$wl)], aic=FALSE, order.max=1)
ar1[i] <- arfit$ar
}
kend <- Kendall(c(1:length(ar1)),ar1)
plot(c(input$wl:(input$wl-1+length(ar1))),ar1,type="l", main=paste('AR(1): Tau=',format(kend$tau, digits=3),sep=""), xlim=c(1,length(ts)),xlab='Index',ylab='AR(1)')
})
output$variplot <- renderPlot({
table <- read.table('tip.txt')
ts <- table[,1]
tscut <- ts[1:input$cut]
smoothed <- ksmooth(c(1:input$cut),tscut,bandwidth=input$bw,x.points=c(1:input$cut))
detrend <- tscut - smoothed$y
vari <- rep(NA, (length(ts)-input$wl))
for (i in 1:(input$cut-input$wl)) {
vari[i] <- var(detrend[i:(i+input$wl)])
}
kend <- Kendall(c(1:length(vari)),vari)
plot(c(input$wl:(input$wl-1+length(vari))),vari,type="l", main=paste('Variance: Tau=',format(kend$tau,digits=3),sep=""),xlim=c(1,length(ts)),xlab='Index',ylab='Variance')
})
})
x <- seq(-2,2,by=0.01) #x axis for plotting
mu <- 2*sqrt(3)/9 #bifurcation parameter
t <- seq(1,1000,by=1) #time steps
m <- mu*t/900 #the change in the bifurcation parameter over time (this is the length of t compared to mu which is a single value)
a <- rep(NA, (length(t)+1)) #setting up vector to hold created time series
a[1] <- -1 #start it in the left well
for (i in 1:length(m)) {
a[i+1] <- a[i] + (1/2)*(-a[i]^3+a[i]+m[i]) + 0.1*rnorm(1)
}
write.table(a,file='tip.txt',col.names=FALSE,row.names=FALSE)
library(shiny)
# Define UI for miles per gallon application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Early Warning Signals"),
sidebarPanel(
sliderInput("bw","Detrending Bandwidth:",min=0.5,max=50,value=10),
sliderInput("wl","Window Length:",min=250,max=650,value=425),
numericInput("cut", "Cut-off point:", 875)
),
mainPanel(
plotOutput("tsplot"),
plotOutput("ar1plot"),
plotOutput("variplot")
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment