
# This is the server logic for a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
#***********************************************************************
# LOAD LIBRARIES
#***********************************************************************
library(fastICA)
library(plotly)
library(mAr)
library(shiny)

#***********************************************************************
# DATA REQUIRED
#***********************************************************************
data(waves)
input_data <- data.frame(sinusoidal = sin((1:1000)/20), triangular = rep((((1:200)-100)/100), 5),
                    rectangular = rep(c(rep(1,1,100),(1:100)*0),5),random = rnorm(1000,1,1),
                    wave1 = waves$wire.gauge[101:1100], wave2 = waves$ir.gauge[1301:2300])
names = c("sinusoidal","triangular","rectangular","random","wave1","wave2")

#***********************************************************************
# SERVER FUNCTION
#***********************************************************************
shinyServer(function(input, output) {
  # Selection
  sel <- reactive({
    c(rep(1:length(names))[names == input$source1],rep(1:length(names))[names == input$source2])
  })
  # Original time series
  S2 <- reactive({
    s2 = as.matrix(cbind(input_data[sel()[1]],input_data[sel()[2]]))
  })
  # data Frame original time series
  S2frame <- reactive({
    N <- nrow(S2())
    #noise <- cbind(rnorm(n = N,mean = 0,sd = 0.5),rnorm(n = N,mean = 0,sd = 0.05))
    noise <- matrix(1, nrow = 1, ncol = 2) %x% rnorm(n = N,mean = 0,sd = input$sd)
    time <- seq(from = 0, by = 0.01,length.out = N)
    aux <- data.frame(var1 = S2()[,1],var2 = S2()[,2],noise = noise[,1],time = time)
    names(aux) <- c(names[sel()[1]],names[sel()[2]],"noise","time")
    S2frame <- aux
  })
  # Create recorded time series frame
  X2frame <- reactive({
    N <- nrow(S2())
    A2 <- matrix(c(0.291, 0.6557, -0.5439, 0.5572), 2, 2)
    noise <- matrix(1, nrow = 1, ncol = 2) %x% as.matrix(S2frame()$noise)
    X2 <- S2() %*% A2 + noise
    X2frame <- data.frame(signal1 = X2[,1],signal2 = X2[,2],time = S2frame()$time)
  })
  # Create ICA data frame
  ICAframe <- reactive({
    # ICA algortihm
    X2 <- as.matrix(cbind(X2frame()$signal1,X2frame()$signal2))
    a2 <- fastICA(X2, 2, alg.typ = "parallel", fun = "logcosh", alpha = 1,
                  method = "R", row.norm = FALSE, maxit = 200,
                  tol = 0.0001, verbose = TRUE)
    # Create ICA components frame
    ICAframe <- data.frame(sourceICA1 = a2$S[,1],sourceICA2 = a2$S[,2],time = S2frame()$time)
  })
  # Plot Signal recorded
  output$RecordedSignals <- renderPlotly({
    # Plot recorded signals
    subplot(
      plot_ly(X2frame(), x = time, y = signal1, type = "l"),
      plot_ly(X2frame(), x = time, y = signal2, type = "l"),
      margin = 0.05,
      nrows = 2
    ) %>% layout(showlegend = FALSE)
  })
  # Plot original sources
  output$OriginalSources <- renderPlotly({
    subplot(
      plot_ly(S2frame(), x = time, y = S2frame()[,names[sel()[1]]], type = "l")%>%layout(yaxis = list(title = names[sel()[1]])),
      plot_ly(S2frame(), x = time, y = S2frame()[,names[sel()[2]]], type = "l")%>%layout(yaxis = list(title = names[sel()[2]])),
      margin = 0.05,
      nrows = 2
    ) %>% layout(main = "Prova",showlegend = FALSE)
  })
  # Plot ICA sources
  output$ICASources <- renderPlotly({
    subplot(
      plot_ly(ICAframe(), x = time, y = sourceICA1, type = "l"),
      plot_ly(ICAframe(), x = time, y = sourceICA2, type = "l"),
      margin = 0.05,
      nrows = 2
    ) %>% layout(showlegend = FALSE)
  })  
})
