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

```{r setup, include=FALSE}
#setwd("~/Documents/my_papers/number/subitizing_info_theory/nature_human_behavior/shiny_tutorial/ex2")
library(shiny)
library(ggplot2)
library(dplyr)
library(shinythemes)

knitr::opts_chunk$set(echo = TRUE)
```


```{r, echo=FALSE}
#library(ggExtra)

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))  

#c1 <- brewer.pal(n=10, "PuBuGn")[4:8]

df <- read.csv("o1.csv")
df <- subset(df, df$alpha == 2)
df$id <- seq.int(1,nrow(df))

unique_info <- unique(df$info)
info_step <- (unique_info[2] - unique_info[1])


df <- df %>%
      group_by(n,info) %>%
      mutate(mean_guess=sum(k*Q_kn)) %>%
      mutate(sd_guess= sum(Q_kn * (mean_guess-k)**2)**0.5) %>%
      mutate(abs_err = sum(Q_kn * abs(n-k))) %>%
      top_n(n=1,wt=id)

```


```{r,echo=FALSE}

ui <- fluidPage(

  titlePanel(""),
  theme = shinytheme("united"),

  fluidRow(
  
    column(3,
      wellPanel(
        sliderInput(inputId = "info",
                  label = "Bits:",
                  min = min(df$info),
                  max = max(df$info),
                  value = min(df$info),
                  step = info_step)
      )),
      column(4,
        plotOutput(outputId = "distPlot1",height="225px")
      ),
      column(4,
        plotOutput(outputId = "distPlot2",height="225px")
      ))

)

```


```{r,fig.width=5,fig.height=4,echo=FALSE}

fmt_dcimals <- function(decimals=0){
   # return a function responpsible for formatting the 
   # axis labels with a given number of decimals 
   function(x) as.character(round(x,decimals))
}


server <- function(input, output) {


  output$distPlot1 <- renderPlot({
    data <- subset(df, (df$info==input$info))

    ggplot(data=data,aes(x=n,y=mean_guess)) +
        geom_line() +
        paper_theme + xlab("Number shown") + ylab("Estimate") +
        scale_color_gradientn(colors=c("blue","red","orange")) +
        coord_cartesian(xlim=c(0,max(df$n)),ylim=c(0,max(df$n)))
    
      }
    )
  
  output$distPlot2 <- renderPlot({
    data <- subset(df, (df$info==input$info))


    ggplot(data=data,aes(x=n,y=abs_err)) +
        geom_line() +
        paper_theme + xlab("Number shown") + ylab("Absolute error") + 
        scale_color_gradientn(colors=c("blue","red","orange")) +
        coord_cartesian(xlim=c(1,max(df$n))) 
    
      }
    )
  
}



```


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

```
