---
title: ""
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(dplyr)
library(shiny)
library(shinythemes)
```


```{r, echo=FALSE}

paper_theme <- theme_light() + theme( axis.title.x = element_text(size=18),
  axis.text.x=element_text(colour="black", 
                           size = 14), 
  axis.title.y = element_text(size = 18, vjust = 1),
  axis.text.y  = element_text(size = 14),
  strip.text=element_text(size=16),
  axis.line.x = element_line(colour = "black"), 
  axis.line.y = element_line(colour = "black"),
  legend.title=element_text(size=18),
  legend.text=element_text(size=16))  


optimal <-list(c(1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0),
c(0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0),
c(0.0001,0.1194,0.8506,0.0299,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0),
c(0.0002,0.0174,0.3003,0.5722,0.1081,0.0019,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0),
c(0.0008,0.0121,0.1018,0.3335,0.384,0.1482,0.0187,0.0008,0.0,0.0,0.0,0.0,0.0,0.0,0.0),
c(0.0023,0.0118,0.055,0.1653,0.2892,0.2808,0.1476,0.0413,0.0061,0.0005,0.0,0.0,0.0,0.0,0.0),
c(0.0047,0.0125,0.0384,0.0969,0.1811,0.2393,0.2178,0.1346,0.0559,0.0155,0.0029,0.0003,0.0,0.0,0.0),
c(0.0079,0.0135,0.0307,0.0657,0.1187,0.173,0.1983,0.1761,0.12,0.0623,0.0245,0.0073,0.0016,0.0003,0.0),
c(0.0115,0.0147,0.0267,0.0494,0.0839,0.1244,0.1572,0.1666,0.1467,0.1066,0.0637,0.0311,0.0124,0.004,0.0011),
c(0.016,0.0162,0.0247,0.0405,0.064,0.0931,0.1216,0.1404,0.1419,0.1248,0.095,0.0624,0.0352,0.0171,0.0071),
c(0.0219,0.0185,0.0243,0.0357,0.0525,0.0737,0.0963,0.1154,0.1255,0.1232,0.1085,0.0856,0.0602,0.0377,0.021))


xs <- seq.int(1,15,1.)
p1 <- 1/(xs**2)
p1 <- p1/sum(p1)
f_kl <- function(p1,p2) {
  sum(p2 * (log2(p2+1e-15) - log2(p1+1e-15)))
}

df_p1 <- data.frame(xs=xs,p1=p1)

```



```{r,echo=FALSE}


ui <- fluidPage(

  titlePanel(""),
  theme = shinytheme("united"),
  fluidRow(
    column(3,
           fluidRow(
              column(12, actionButton("reset", "New Number"))
           ),
           br(),
           fluidRow(
              column(12, actionButton("norm", "Re-Normalize"))
           ),
            br(),
            fluidRow(
              column(12, actionButton("opt", "Show Optimal"))
           )

      ),

    column(8, plotOutput(outputId = "distPlot1",width="500px",height="350px", click="plot_click"))#,

  )

)


```

```{r,echo=FALSE}
plot_clicks_y <<- rep(0.05,15)
#plot_clicks_y <<- plot_clicks_y/sum(plot_clicks_y)

#n <- sample(1:11, 1)
ns <<- c(10)


server <- function(input, output) {
  rp <-function() { renderPlot({
    
      n <- ns[1]

    
  
     
      if ((!is.null(input$plot_click$x)) & (!(is.null(input$plot_click$y)))) {
        inp_x <- min(max(round(input$plot_click$x),1),15)
        inp_y <- min(max(input$plot_click$y,0.000001),1.)
        if (inp_y > 0.99) {
          plot_clicks_y <<- plot_clicks_y * (1.-inp_y)
        }
        plot_clicks_y[inp_x] <<- inp_y

  
      }
     # plot_clicks_y <<- plot_clicks_y/sum(plot_clicks_y)
  #       
      p2 <- plot_clicks_y/sum(plot_clicks_y)
      sq_err <- round(sum(p2 * (n-xs)**2),2)

      kl <- round(f_kl(p1,p2),2)
      if (kl > 3.) {
        col<- "red"
      } else {
        col <- "darkgreen"
      }
  
      df_p2 <- data.frame(xs=xs,plot_clicks_y=plot_clicks_y,
                          p2=p2,kl=kl,sq_err=sq_err)
      ylim_high <- max(min(max(p2)*2,1), max(p1))
      p.1 <- ggplot() +
          geom_area(data=df_p1,aes(x=xs,y=p1,color="P",fill="P"),alpha=0.5) +
          geom_line(data=df_p1,aes(x=xs,y=p1,color="P",fill="P"),alpha=0.8) +
          geom_point(data=df_p1,aes(x=xs,y=p1,color="P",fill="P"),alpha=0.1) +
          geom_area(data=df_p2,aes(x=xs,y=plot_clicks_y,color="Q",fill="Q"),alpha=0.4) +
          geom_line(data=df_p2,aes(x=xs,y=plot_clicks_y,color="Q",fill="Q"),alpha=0.8) +
       geom_point(data=df_p2,aes(x=xs,y=plot_clicks_y,color="Q",fill="Q"),alpha=0.1) +

        #geom_area(data=df_p2,aes(x=xs,y=p2,color="Q",fill="Q"),alpha=0.3) +
        #geom_line(data=df_p2,aes(x=xs,y=p2,color="Q",fill="Q"),alpha=0.3) +
        #geom_col(data=df_p2,aes(x=xs,y=plot_clicks_y,color="Q",fill="Q"),alpha=0.2,width=0.1) +
        #geom_point(data=df_p2,aes(x=xs,y=plot_clicks_y,color="Q",fill="Q"),alpha=1.) +
        geom_vline(linetype="dotted",xintercept=n,size=1.5) +
  
          scale_fill_manual(values=c("blue","orange")) +
          scale_color_manual(values=c("blue","orange")) +
          geom_label(aes(x=4.5,y=0.95, label=paste("KL =", kl)),size=6,alpha=0.5,color=col) +
            geom_label(aes(x=9.5,y=0.95, label=paste("Error =", round(sq_err,1))),size=6,alpha=0.5) +
  
        coord_cartesian(ylim=c(0,1),xlim=c(1,15)) +
                guides(color=FALSE) +
            xlab("n") + ylab("P(n)") +
          paper_theme + theme(legend.title=element_blank(),
                            legend.position=c(0.82,0.9))


        return(p.1)
  
     })
  }
    observeEvent(input$reset, {
      n <- ns[1]
      if (n == 10) {
        
        ns <<- c(sample(1:2,1))
      } else {
        
        ns <<- c(sample(1:11, 1))

      }
      n <- ns[1]

      #plot_clicks_y <<- rep(1,15)
      #plot_clicks_y <<- plot_clicks_y/sum(plot_clicks_y)

      plot_clicks_y <<- rep(0.05,15)

      output$distPlot1 <- rp()
    
    
  })

  observeEvent(input$norm, {
      plot_clicks_y <<- plot_clicks_y / sum(plot_clicks_y)
      output$distPlot1 <- rp()

  })
  
  observeEvent(input$opt, {
      n <- ns[1]

      plot_clicks_y <<- as.numeric(unlist(optimal[n]))
      plot_clicks_y <<- plot_clicks_y / sum(plot_clicks_y)

      output$distPlot1 <- rp()

  })
  
  
  
  output$distPlot1 <- rp()

    # output$mytable = DT::renderDataTable({
    #   best_df
    # }, options = list(dom = 'tp',  pageLength = 6,rownames=FALSE))
}


```



```{r,echo=FALSE}
shinyApp(ui,server)

```