# ----------------------------------------
#  App Title: Benford's Law and Sequences
#     Author: Jimmy Doi
# ----------------------------------------
library(shinyIncubator)

shinyUI(navbarPage("Benford's Law: Sequences",

###################################################################################################
## tabPanel: Additive Sequence                                                                   ##
###################################################################################################
tabPanel("(1) Additive Sequence",
   fluidPage(
       tags$head(tags$link(rel = "icon", type = "image/x-icon", href =
       "https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico")),

       progressInit(),

       # Give the page a title
       h3("Benford's Law: Additive Sequence"),

        div("Note: Please adjust width of browser if only one column is visible.",br(),
            HTML("[Click here for another Shiny app on Benford's Law]"),
            style = "font-size: 9pt;color:teal"),br(),

       p("Consider a sequence of numbers where we fix the initial two numbers and then the
         value of each subsequent number is the sum of the previous two. We will call this an",
         tags$b("additive sequence."),
         "When the initial two numbers are both 1 then this yields the famous Fibonacci sequence.
         If you only consider the first digit of each number in an additive sequence and examine its distribution,
         is it the case that it closely follows ",
         HTML("Benford's Law?"),
         "This app generates an additive sequence, for a given length and initial sequence numbers,
         and applies a goodness of fit test of the observed frequencies of first digits to Benford's Law",
         style="font-size:11pt"),
       HTML("
"),

       # Generate a row with a sidebar
       fluidRow(

         column(4,wellPanel(

           sliderInput("seq1",
                       label = h5("First Sequence Number"),
                       min = 1, max = 9, value = 1, step=1),br(),

           sliderInput("seq2",
                       label = h5("Second Sequence Number"),
                       min = 1, max = 9, value = 1, step=1),br(),

           sliderInput("length",
                       label = h5(HTML("Length of sequence (n)")),
                       min = 150, max = 1000, value = 150, step=50),br(),

           br(), br(), br(), br(),

           div("Shiny app by",
               a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
                 "Jimmy Doi"),align="right", style = "font-size: 8pt"),

           div("Base R code by",
               a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
                 "Jimmy Doi"),align="right", style = "font-size: 8pt"),

           div("Shiny source files:",
               a(href="https://gist.github.com/calpolystat/f4475cbfe4cc77cef168",
                 target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

           div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
                 "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
         )),
         column(8,
          div(span(tags$b("First 50 numbers in the sequence (first digit in"),style="font-size:9pt"),
              span(
                span("red",style="font-size:9pt; color:red; font-weight:bold"),tags$b("):",
                conditionalPanel("input.seq1==1 & input.seq2==1",
                  span(HTML("   "),"[Fibonacci sequence]",
                  style="text-align: right;color:blue;font-size:9pt;display:inline-block"),
                  style="text-align: right;font-size:0pt;display:inline-block;"),
                conditionalPanel("input.seq1==2 & input.seq2==1",
                  span(HTML("   "),"[Lucas sequence]",
                  style="text-align: right;color:blue;font-size:9pt;display:inline-block"),
                  style="text-align: right;font-size:0pt;display:inline-block;"),style="font-size:9pt")),
              style="font-size:0pt"),
          div(
            div(span(textOutput("num.1a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.1b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.2a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.2b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.3a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.3b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.4a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.4b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.5a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.5b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.6a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.6b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.7a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.7b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.8a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.8b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.9a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.9b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.10a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.10b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.11a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.11b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.12a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.12b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.13a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.13b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.14a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.14b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.15a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.15b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.16a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.16b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.17a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.17b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.18a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.18b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.19a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.19b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.20a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.20b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.21a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.21b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.22a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.22b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.23a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.23b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.24a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.24b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.25a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.25b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.26a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.26b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.27a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.27b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.28a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.28b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.29a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.29b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.30a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.30b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.31a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.31b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.32a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.32b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.33a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.33b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.34a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.34b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.35a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.35b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.36a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.36b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.37a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.37b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.38a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.38b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.39a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.39b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.40a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.40b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.41a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.41b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.42a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.42b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.43a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.43b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.44a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.44b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.45a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.45b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.46a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.46b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.47a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.47b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.48a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.48b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.49a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.49b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.50a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.50b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                span("",style="font-size: 9pt"),style="display:inline-block"),
            style="font-size:0;"),

          div(span("[Sequence has ",style="text-align: right;font-size:9pt;display:inline-block"),
              span(HTML(" "),style="text-align: right;font-size:9pt"),
              span(textOutput("textlength"),style="text-align: right;font-size:9pt;display:inline-block;color:teal"),
              span(HTML(" "),style="text-align: right;font-size:9pt"),
              span("numbers total]",style="text-align: right;font-size:9pt;display:inline-block"),
                                                         style="text-align: right;font-size:0pt;display:inline-block;"),

          HTML("
"),

          fluidRow(
            column(4,
                   p(tags$b("Goodness of Fit Test")),
                   verbatimTextOutput("goodness")),
            column(8,
                   plotOutput("pmf")
            )#closes column-8
          ),#closes fluidRow
          HTML("
")
       ) # closes column-8
    ) #closes fluidRow
  ) #closes fluidPage
), #close tabPanel#1

###################################################################################################
## tabPanel: Power Sequence                                                                     ##
###################################################################################################
tabPanel("(2) Power Sequence",
  fluidPage(

  # Give the page a title
  h3("Benford's Law: Power Sequence"),

  div("Note: Please adjust width of browser if only one column is visible.",br(),
  HTML("[Click here for another Shiny app on Benford's Law]"),
      style = "font-size: 9pt;color:teal"),br(),

  p("Consider a sequence of the form",
  HTML("b1, b2, …, b n, "),
  "where ", tags$em("b"), "is called the base.
  We will call this a ", HTML("power sequence."), "
  If you only consider the first digit of each number in a power sequence and examine its distribution,
  is it the case that it closely follows ",
  HTML("Benford's Law?"),
    "This app generates the power sequence, for a given", HTML("b and n,"),
    "and applies a goodness of fit test of the observed frequencies of first digits to Benford's Law.",
    style="font-size:11pt"),
  HTML("
"),

  fluidRow(

    column(4,wellPanel(

      sliderInput("pow.base",
                  label = h5(HTML("Base value (b)")),
                  min = 2, max = 9, value = 2, step=1),br(),

      sliderInput("pow.length",
                  label = h5(HTML("Length of sequence (n)")),
                  min = 150, max = 300, value = 150, step=10),br(),

      br(), br(), br(), br(),

      div("Shiny app by",
          a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
            "Jimmy Doi"),align="right", style = "font-size: 8pt"),

      div("Base R code by",
          a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
            "Jimmy Doi"),align="right", style = "font-size: 8pt"),

      div("Shiny source files:",
          a(href="https://gist.github.com/calpolystat/f4475cbfe4cc77cef168",
            target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

      div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
            "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
    )),
    column(8,
      div(span(tags$b("First 20 numbers in the sequence (first digit in"),style="font-size:9pt"),
          span(
            span("red",style="font-size:9pt; color:red; font-weight:bold"),tags$b("):",style="font-size:9pt")),
          style="font-size:0pt"),
      div(
        div(span(textOutput("e.num.1a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.1b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.2a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.2b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.3a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.3b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.4a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.4b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.5a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.5b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.6a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.6b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.7a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.7b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.8a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.8b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.9a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.9b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.10a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.10b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.11a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.11b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.12a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.12b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.13a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.13b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.14a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.14b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.15a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.15b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.16a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.16b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.17a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.17b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.18a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.18b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.19a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.19b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.20a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.20b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            span("",style="font-size: 9pt"),style="display:inline-block"),
        style="font-size:0;"),
      div(span("[Sequence has ",style="font-size:9pt;display:inline-block"),
          span(HTML(" "),style="font-size:9pt"),
          span(textOutput("powlength"),style="font-size:9pt;display:inline-block;color:teal"),
          span(HTML(" "),style="font-size:9pt"),
          span("numbers total]",style="font-size:9pt;display:inline-block"),style="font-size:0pt;display:inline-block;",align="right"),

      HTML("
"),
      fluidRow(
        column(4,
               p(tags$b("Goodness of Fit Test")),
               verbatimTextOutput("e.goodness")),
        column(8,
               plotOutput("e.pmf")
              ) #closes column-8
            ), #closes fluidRow
          HTML("
")
        ) #closes column-8
     ) #closes fluidRow
  ) #closes fluidPage
), #close tabPanel#2

###################################################################################################
## tabPanel: Prime Numbers Sequence                                                              ##
###################################################################################################
tabPanel("(3) Prime Numbers Sequence",
  fluidPage(

    # Give the page a title
    h3("Generalized Benford's Law: Prime Numbers Sequence"),

    div("Note: Please adjust width of browser if only one column is visible.",br(),
        HTML("[Click here for another Shiny app on Benford's Law]"),
        style = "font-size: 9pt;color:teal"),br(),

    p("Consider the sequence of prime numbers less than or equal to some power of 10. An article from 2009
      shows that the distribution of the first digit of these prime numbers
      is well described by what's known as", HTML("Generalized Benford's Law (GBL)"),".
      This app generates the prime numbers less than or equal to", HTML("103, 104,
      105, or 106"), "and applies a goodness of fit test of the observed frequencies of first digits to GBL."
      ),

    p("More information on the Generalized Benford's Law can be found in the following journal article:"),

    div("Luque, B. and Lacasa, L.(2009)",
        HTML("'The first-digit frequencies of prime numbers and Riemann zeta zeros'"),
        em("Proc. R. Soc. A"),", 465, 2197-2216", style="padding-left: 20px; display:block; border-left: 5px solid #faebbc;margin-left:0px"),

    HTML("
"),

    # Generate a row with a sidebar
    fluidRow(

      column(4,wellPanel(

        selectInput("my.n", label = h5("Generate sequence of prime numbers less than or equal to"),
                    choices = list("1,000" = 1000, "10,000" = 10000, "100,000" = 100000, "1,000,000" = 1000000),
                    selected = 1000),

        br(), br(), br(), br(),

        div("Shiny app by",
            a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
              "Jimmy Doi"),align="right", style = "font-size: 8pt"),

        div("Base R code by",
            a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
              "Jimmy Doi"),align="right", style = "font-size: 8pt"),

        div("Shiny source files:",
            a(href="https://gist.github.com/calpolystat/f4475cbfe4cc77cef168",
              target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

        div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
              "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
      )),
      column(8,
        div(span(tags$b("First 80 numbers in the sequence (first digit in"),style="font-size:9pt"),
            span(
              span("red",style="font-size:9pt; color:red; font-weight:bold"),tags$b("):",style="font-size:9pt")),
            style="font-size:0pt"),
        div(
          div(span(textOutput("pr.num.1a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.1b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.2a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.2b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.3a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.3b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.4a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.4b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.5a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.5b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.6a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.6b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.7a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.7b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.8a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.8b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.9a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.9b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.10a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.10b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.11a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.11b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.12a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.12b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.13a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.13b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.14a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.14b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.15a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.15b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.16a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.16b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.17a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.17b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.18a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.18b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.19a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.19b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.20a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.20b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.21a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.21b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.22a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.22b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.23a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.23b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.24a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.24b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.25a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.25b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.26a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.26b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.27a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.27b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.28a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.28b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.29a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.29b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.30a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.30b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.31a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.31b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.32a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.32b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.33a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.33b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.34a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.34b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.35a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.35b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.36a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.36b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.37a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.37b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.38a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.38b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.39a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.39b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.40a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.40b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.41a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.41b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.42a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.42b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.43a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.43b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.44a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.44b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.45a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.45b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.46a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.46b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.47a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.47b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.48a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.48b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.49a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.49b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.50a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.50b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.51a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.51b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.52a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.52b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.53a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.53b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.54a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.54b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.55a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.55b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.56a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.56b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.57a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.57b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.58a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.58b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.59a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.59b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.60a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.60b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.61a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.61b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.62a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.62b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.63a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.63b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.64a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.64b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.65a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.65b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.66a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.66b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.67a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.67b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.68a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.68b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.69a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.69b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.70a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.70b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.71a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.71b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.72a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.72b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.73a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.73b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.74a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.74b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.75a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.75b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.76a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.76b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.77a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.77b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.78a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.78b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.79a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.79b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.80a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.80b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          style="font-size:0;"),
        div(span("[Sequence has ",style="font-size:9pt;display:inline-block"),
            span(HTML(" "),style="font-size:9pt"),
            span(textOutput("num.primes"),style="font-size:9pt;display:inline-block;color:teal"),
            span(HTML(" "),style="font-size:9pt"),
            span("prime numbers total]",style="font-size:9pt;display:inline-block"),style="font-size:0pt;display:inline-block;",align="right"),

        HTML("
"),
        fluidRow(
          column(4,
                 p(tags$b("Goodness of Fit Test")),
                 verbatimTextOutput("pr.goodness")),
          column(8,
                 plotOutput("pr.pmf")
              ) # closes column-8
            ), #closes fluidRow
          HTML("
")
        ) #closes column-8
     ) #closes fluidRow
  ) #closes fluidPage
) #closes tabPanel#3
) #closes navbarPage
) #closes shinyUI


 ZHPGVD Example Program Results

 Eigenvalues
      -61.7321    -6.6195     0.0725    43.1883

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates (relative to machine precision)
 for the eigenvalues:
        2.4E+04    2.8E+03    2.3E+02    1.7E+04


#!/usr/bin/Rscript

# Travelling Salesmen Problem library
library(TSP)

# --- SETTINGS ---
# Distance matrix input file
distance_matrix_input <- "~/Desktop/cities 3.tsv"

# Set the method (e.g. nearest_insertion or cheapest_insertion) of the TSP library
global_method <- "nearest_insertion"

# Check if the distance matrix is symmetric
check_distance_matrix_symmetric <- FALSE

# Read cities data (distance matrix) from TSV file
data<-read.csv(distance_matrix_input, sep = "\t", header=TRUE, row.names = 1)

# Check if distance matrix is symmetric
if (check_distance_matrix_symmetric) {
	isSymmetric(t(data))
}

do_tsp <- function(data, start, used_method) {
	d<-dist(data)
	tsp <- TSP(d)
	initial_tour <- solve_TSP(tsp, method = used_method, control=list(start=start))

	# Refine
	tour <- solve_TSP(tsp, method="two_opt", control=list(tour=initial_tour))

	return(tour)
}

# Sum all distances between cities in the tour
calculate_tour_length <- function(data, tour) {
	tourlength <- 0

	for (i in 1:(length(names(tour))-1)) {
		tourlength <- tourlength + as.integer(data[names(tour)[i],names(tour)[i+1]])
	}

	# Last city back to the first one
	tourlength <- tourlength + as.integer(data[names(tour)[i+1],names(tour)[1]])

	return(tourlength)
}

# Print all stages of the tour
print_stages <- function(data, tour) {

	for (i in 1:(length(names(tour))-1)) {
		print(paste(names(tour)[i], "->", names(tour)[i+1], ":", as.integer(data[names(tour)[i],names(tour)[i+1]])))
	}

	# Last city back to the first one
	print(paste(names(tour)[i+1], "->", names(tour)[1], ":", as.integer(data[names(tour)[i+1],names(tour)[1]])))
}

# Calculate tours

print("Distance matrix: ")
print(data)

print("")
print("TSP method used: ")
print(global_method)

# All cities
print("")
print("All cities")
tour <- do_tsp(data, 7L, global_method)

labels(tour)
print_stages(data, tour)

tourlength <- calculate_tour_length(data, tour)
print(paste("Total tour length:", tourlength))

# All cities east of LV (inclusive)
print("")
print("All cities east of LV, start and end in SF")
tour <- do_tsp(data[-(2:6),-(2:6)], 2L, global_method)

labels(tour)
print_stages(data, tour)

tourlength <- calculate_tour_length(data, tour)
print(paste("Total tour length:", tourlength))

# All cities west of LV (inclusive)
print("")
print("All cities west of LV, start and end in LV")
tour <- do_tsp(data[1:6,1:6], 1L, global_method)

labels(tour)
print_stages(data, tour)

tourlength <- calculate_tour_length(data, tour)
print(paste("Total tour length:", tourlength))


costsalary <- read.csv("/Users/sashabouloudnine/Desktop/r/data/costsalary.csv")

y=costsalary$Salary
x=costsalary$Costs

summary(y)
summary(x)

model1=lm(y~x)
summary(model1)

plot(x,y)
abline(lm(y~x))
abline(a=model1$coefficients[1],b=model1$coefficients[2],col="red")

mean(model1$residuals)
plot(model1$residuals)


# Reading in data

ds = read.csv('Ads_CTR.csv')

# Random sample

N = 10000
d = 10

random_reward = 0
for (n in 1:N) {
    ad = sample(1:d, 1)
    random_reward = total_reward + ds[n,ad]
}

## UCB algorithm

# Initialising
ads_selected = seq(1,10)
num_selections = rep(1,10)
sum_rewards = ds[1,]
total_reward = sum(sum_rewards)

# For each round, choose the ad with the maximum UCB
for (n in 2:N) {
    ad = 1
    max_upper_bound = 0

    for (i in 1:d) {
        rbar = sum_rewards[i]/num_selections[i]
        delta_i = sqrt(3/2 *log(n + 1)/num_selections[i])
        ucb = rbar + delta_i

        if (ucb > max_upper_bound){
            ad = i
            max_upper_bound = ucb
        }
    }
    ads_selected = append(ads_selected,ad)
    num_selections[ad] = num_selections[ad] + 1

    reward = ds[n, ad]
    sum_rewards[ad] = sum_rewards[ad] + reward
    total_reward = total_reward +  reward
}

# Visualising results
hist(ads_selected,
     main = 'Histogram of ads selected',
     col = 'blue',
     xlab = 'Ads',
     ylab = 'Ad selection frequency density')


library(e1071)

source("number.r")

analyze_univariate_data <- function(data, context) {
    analysis <<- c()

    add_analysis <- function(text) {
        analysis[length(analysis) + 1] <<- text
    }

    data <- sort(data)

    summary <- quantile(data)
    iqr <- round(summary[[4]] - summary[[2]], 4)
    lower_fence <- summary[[2]] - 1.5 * iqr
    upper_fence <- summary[[4]] + 1.5 * iqr

    skew <- skewness(data)
    skewed <- skew > 0.5 | skew < -0.5

    # center
    if (skewed) {
        med <- round(median(data), 4)
        add_analysis(paste(c("The", context, "have a median of", med), collapse = " "))
    } else {
        mean <- round(mean(data), 4)
        add_analysis(paste(c("The", context, "have a mean of", mean), collapse = " "))
    }

    # outliers
    outliers <- c()
    for (value in data) {
        if (value < lower_fence) {
            outliers[length(outliers) + 1] <- value
        } else if (value > upper_fence) {
            outliers[length(outliers) + 1] <- value
        }
    }

    if (length(outliers) == 1) {
        add_analysis(paste(c("There is one outlier of", outliers[1]), collapse = " "))
    } else if (length(outliers) > 1) {
        outliers_list <- c(paste(outliers[1:length(outliers) - 1], collapse = ", "), "and", outliers[length(outliers)])
        add_analysis(paste(c("There are", length(outliers), "outliers:", outliers_list), collapse = " "))
    }

    # normality
    #data <- sort(rnorm(100))
    positions <- 1:length(data)
    percentiles <- ((positions - 0.5) / length(positions)) * 100
    percentile_zscores <- (percentiles - mean(percentiles)) / sd(percentiles)
    normal_probability_correlation <- cor(data, percentile_zscores)

    if (normal_probability_correlation > 0.975) {
        add_analysis(paste("The distribution of the", context, "appears to be normal", collapse = " "))
    }

    # shape
    if (skew > 1.5) {
        add_analysis(paste("The", context, "are heavily skewed to the right", collapse = " "))
    } else if (skew > 0.5) {
        add_analysis(paste("The", context, "are skewed right", collapse = " "))
    } else if (skew < -0.5) {
        add_analysis(paste("The", context, "are skewed left", collapse = " "))
    } else if (skew < -1.5) {
        add_analysis(paste("The", context, "are heavily skewed to the left", collapse = " "))
    }

    # spread
    if (length(outliers) == 0) {
        range <- max(data) - min(data)
        add_analysis(paste(c("The", context, "have a range of", range), collapse = " "))
    } else {
        add_analysis(paste(c("The", context, "have a standard deviation of", round(sd(data), 4), "and an IQR of", iqr), collapse = " "))
    }

    hist(data)
    return(paste(c(paste(analysis, collapse = ". "), "."), collapse = ""))
}


df <- read.csv(textConnection(
"C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20"))

df <- transform(df,SUM = rowSums(df))

write.csv(df,row.names = FALSE)


#==============================================================================
#	Unit test of MESS calculation
#==============================================================================
library(testthat)
library(cv.models)

#------------------------------------------------------------------------------
context("Unit test for MESS calculation")

#------------------------------------------------------------------------------
test_that(
	"Test correctness of MESS using single variable",
	{
		data.train <- data.frame(a = 0:100)
		data.test <- data.frame(
			a = c(-50, -1, 0, 1, 50, 51, 52, 100, 101, 102, 150)
		)
		expected <- c(
			# if fi = 0: (pi - mini) / (maxi - mini) * 100
			(-50 - 0) / (100 - 0) * 100,
			(-1 - 0) / (100 - 0) * 100,
			(0 - 0) / (100 - 0) * 100,
			# if 0 < fi ≤ 50: 2 * fi
			2 * 1 / length(0:100) * 100,
			2 * 50 / length(0:100) * 100,
			# if 50 ≤ fi < 100: 2 * (100 - fi)
			2 * (100 - (51 / length(0:100)) * 100),
			2 * (100 - (52 / length(0:100)) * 100),
			2 * (100 - (100 / length(0:100)) * 100),
			# if fi = 100: (maxi - pi) / (maxi - mini) * 100
			(100 - 101) / (100 - 0) * 100,
			(100 - 102) / (100 - 0) * 100,
			(100 - 150) / (100 - 0) * 100
		)
		result <- cv.models:::calculate.mess(data.train, data.test, TRUE)
		expect_equal(result, expected)
	}
)

#------------------------------------------------------------------------------
test_that(
	"Test MESS using multiple variables can select lowest values",
	{
		data.train <- data.frame(a = 0:100, b = 0:100)
		data.test <- data.frame(a = c(-50, 1, 50), b = c(-1, 0, 51))
		expected <- c(
			(-50 - 0) / (100 - 0) * 100,
			(0 - 0) / (100 - 0) * 100,
			2 * 50 / length(0:100) * 100
		)
		result <- cv.models:::calculate.mess(data.train, data.test, TRUE)
		expect_equal(result, expected)
	}
)


primes <- as.integer(c())

max_prime_checker <- function(n){
  divisor <<- NULL

  primes <- primes[primes <= n]

  for(i in 1:length(primes)){
    if((n/primes[i]) %% 1 == 0){
      divisor[i]<<-1
    } else {
      divisor[i]<<-0
    }
  }
  num_find <<- primes*as.integer(divisor)

  return(max(num_find))
}

#recursive prime finder
prime_factors <- function(n){

  factors <- NULL

  large <- max_prime_checker(n)
  n1 <- n/large

  if(max_prime_checker(n1) == n1){
    factors <- c(large,n1)
    return(factors)
  } else {
    factors <- c(large, prime_factors(n1))
    return(factors)
  }
}


r_pacf_1 = ARMAacf(ar=c(1.3, -0.24), lag.max=20, pacf=TRUE)
print('For AR(2) process')
cat('l=1',r_pacf_1[1])
cat('l=2',r_pacf_1[2])

r_pacf_2 = ARMAacf(ma=c(0.6), lag.max=20, pacf=TRUE)
print('For MA(1) process')
cat('l=1',r_pacf_2[1])
cat('l=2',r_pacf_2[2])


blkwin <- function(np) {
  rad <- seq(0,2*pi,2*pi/(np-1))
  w <- (.42 - .5*cos(rad) + .08*cos(2*rad))
  return(w)
}

hamwin <- function(np) {
  w <- .54 - .46 * cos(seq(0,2*pi,2*pi/(np-1)))
  return(w)
}

hanwin <- function(np) {
  w <- .5 - .5 * cos(seq(0,2*pi,2*pi/(np-1)))
  return(w)
}


library(extraDistr)
# sample: r, pdf: d, cdf: p, quantile: q

x = 3

lRange = 1; uRange = 9;          rdunif(1,lRange,uRange); ddunif(x,lRange,uRange); pdunif(x,lRange,uRange); qdunif(0.2,lRange,uRange); # from extraDistr
p = 0.8;                         rbern(1,p); dbern(1,p); pbern(1,p); qbern(0.2,p); # from extraDistr
n = 20; p = 0.8;                 rbinom(1,n,p); dbinom(x,n,p); pbinom(x,n,p); qbinom(0.2,n,p);
ps = c(0.2,0.5,0.2,0.1);         rcat(1,ps); dcat(x,ps); pcat(x,ps); qcat(0.2,ps); # from extraDistr

p = 0.2;                         rgeom(1,p); dgeom(x,p); pgeom(x,p); qgeom(0.2,p);
sAv = 10; fAv = 20; nTrials = 3; rhyper(1, sAv, fAv, nTrials); dhyper(x, sAv, fAv, nTrials); phyper(x, sAv, fAv, nTrials); qhyper(0.2, sAv, fAv, nTrials)

rate = 10;                       rpois(1,rate); dpois(x,rate); ppois(x,rate); qpois(0.2,rate)
nSucc =10; p = 0.2;              rnbinom(1, nSucc,p); dnbinom(x, nSucc,p); pnbinom(1, nSucc,p); qnbinom(0.2, nSucc,p);  # Return the number of failures before n successes instead of total trials to n successes

lRange = 1; uRange = 9;          runif(1,lRange,uRange); dunif(x,lRange,uRange); punif(x,lRange,uRange); qunif(0.2,lRange,uRange);
rate = 2.5;                      rexp(1,rate); dexp(x,rate); pexp(x,rate); qexp(0.2,rate);
μ = 2; σsq = 5 ;                 rnorm(1,μ,sqrt(σsq)); dnorm(x,μ,sqrt(σsq)); pnorm(x,μ,sqrt(σsq)); qnorm(0.2,μ,sqrt(σsq));
n = 5; rate = 2.5;               #use gamma, as erlang special case of it when shape is integer
μ = 2.5; σ = 2.5;                rcauchy(1,μ,σ); dcauchy(x,μ,σ); pcauchy(x,μ,σ); qcauchy(0.2,μ,σ)
df = 3;                          rchisq(1,df); dchisq(x,df); pchisq(x,df); qchisq(0.2,df);
df = 4.5;                        rt(1,df); dt(x,df); pt(x,df); qt(0.2,df);
df1 = 6 ; df2 = 7;               rf(1,df1,df2); df(x,df1,df2); pf(x,df1,df2); qf(0.2,df1,df2);
shapeα = 2.5; shapeβ=4.5;        rbeta(1,shapeα,shapeβ); dbeta(x,shapeα,shapeβ); pbeta(x,shapeα,shapeβ); qbeta(0.2,shapeα,shapeβ)
shapeα = 2.5; rateβ = 4.5;       rgamma(1,shapeα,1/rateβ); dgamma(x,shapeα,1/rateβ); pgamma(x,shapeα,1/rateβ); qgamma(0.2,shapeα,1/rateβ)

xs = c(3,12,5)
n=20; ps = c(0.2,0.5,0.3);       rmnom(1,n,ps);  dmnom(xs,n,ps);  # from extraDistr
initialNByCat = c(5,14,7); nTrials=20 ; rmvhyper(1,initialNByCat,nTrials); dmvhyper(xs,initialNByCat,nTrials) # from extraDistr


# Syntax
# matrix(data, nrow, ncol, byrow, dimnames)

myVector <- c(1, 2, 3, 4)

myMatrix <- matrix(myVector, nrow = 2, ncol = 2);
#myMatrix <- matrix(myVector, nrow = 2, ncol = 2, byrow = TRUE)
print(myMatrix)

# Set the names of rows and columns.
rownames = c('r1', 'r2', 'r3', 'r4')
colnames = c('c2', 'c2', 'c3')
myMatrix <- matrix(c(1:12), nrow = 4, ncol = 3, byrow = TRUE, dimnames = list(rownames, colnames))
print(myMatrix)

# Acessing and Manipulating Matrices
myMatrix <- matrix(c(1:12), nrow = 4, byrow = TRUE)
print(myMatrix[2, 3])

# Acessing using single index
myMatrix <- matrix(c(1:12), nrow = 4, byrow = TRUE)
myMatrix[10] = 0
print(myMatrix)


# Example : 6   Chapter : 8.6     Page No: 457
# Singualar Value Decomposition
gradematrixA<-matrix(c(-6,0,4,2,2,4,0,-6,0,-6,2,4,4,2,-6,0),ncol=4)
print("SVD of Grade matrix is")
print(svd(gradematrixA))
#The answers may vary due to rounding off values


#
# Don't complain; just work harder! Dan Stanford
#
# Our responsibility is to do what we can, learn what we can, improve the solutions, and pass them on. RF
#
# @author: me@andreagirardi.it
#
# @prerequisite
#   install.packages('ggplot2')
#   library(ggplot2)
#   library(ggthemes)
#   mtcars

> library(ggplot2)
> library(ggthemes)

# Import data
df <- read.csv('BootcampWithR/Economist_Assignment_Data.csv', sep=',')

print(head(df))

# Use ggplot() + geom_point() to create a scatter plot object called pl. You will need to specify x=CPI and y=HDI and color=Region as aesthetics
> pl <- ggplot(df, aes(x = CPI, y = HDI, color = Region)) + geom_point(shape = 1, size = 4)

# We want to further edit this trend line. Add the following arguments to geom_smooth (outside of aes):
#
# Smoothing method (function) to use, accepts either a character vector, e.g. "auto", "lm", "glm", "gam", "loess" or a function, e.g. MASS::rlm or mgcv::gam, stats::lm, or stats::loess.
# method = 'lm'
#
# Formula to use in smoothing function, eg. y ~ x, y ~ poly(x, 2), y ~ log(x)
# formula = y ~ log(x)
#
# Display confidence interval around smooth? (TRUE by default, see level to control.)
# se = FALSE
#
# color = 'red'
pl2 <- pl + geom_smooth(formula = y ~ log(x), color = "red", method = "lm", se = FALSE)

# Add labels
> p2 + geom_text(aes(label=Country))

> pointsToLabel <- c("Russia", "Venezuela", "Iraq", "Myanmar", "Sudan",
                "Afghanistan", "Congo", "Greece", "Argentina", "Brazil",
                "India", "Italy", "China", "South Africa", "Spane",
                "Botswana", "Cape Verde", "Bhutan", "Rwanda", "France",
                "United States", "Germany", "Britain", "Barbados", "Norway", "Japan",
                "New Zealand", "Singapore")

> pl3 <- pl2 + geom_text(aes(label = Country), color = "gray20", data = subset(df, df$Country %in% pointsToLabel), check_overlap=TRUE)

# Change theme
> pl4 <- pl3 + theme_bw()

# Add scale_x_continuous()
> pl5 <- pl4 + scale_x_continuous(name = "Corruption Perception Index, 2011 (10 = least corrupt)", limits = c(.9, 10.5), breaks=1:10)

# Add scale_y_continous()
> pl6 <- pl5 + scale_y_continuous(name = "Human Development Index, 2011 (1=Best)", limits = c(0.2, 1.0))

# Add graphic title
# To center: theme(plot.title = element_text(hjust = 0.5))
> pl7 <- pl6 + ggtitle(label = "Corruption and Human development") + theme_economist_white() + theme(plot.title = element_text(hjust = 0.5))


library(ggplot2)
source("myPalette.r")

gcd <- function(a, b) {
    while ( (c <- a %% b) != 0 ) {
        a <- b
        b <- c
    }
    b
}

i <- c()
j <- c()
k <- c()

# calculate a data frame with i, j, gcd(i, j) in each row
for (a in c(1 : length(cbPalette))) {
    for (b in (1 : a)) {
        index <- print (a * (a - 1) / 2 + b)
        i[index] <- a
        j[index] <- b
        k[index] <- gcd(a,b)
    }
}

data <- data.frame(i,j,k)
data$gcd <- factor(data$k)

# create a grid of dots with color corresponding to gcd
myPlot <- ggplot(data, aes(i, j)) +
    geom_point(size = 10, aes(color = data$gcd)) +
    scale_color_manual(values = cbPalette,
                       name = "Count",
                       breaks = c(1 : 10),
                       labels = c("32", "10", "4", "2", "2", "1", "1", "1", "1","1")
                       ) +
    scale_x_continuous(breaks = c(1 : 10)) +
    scale_y_continuous(breaks = c(1 : 10)) +
    theme(axis.title.x = element_blank()) +
    theme(axis.title.y = element_blank())

# label each dot with gcd(i, j)
for (n in 1 : nrow(data)) {
    myPlot <- myPlot + annotate("text", x = data[n,]$i, y = data[n,]$j, label = toString(data[n,]$k))
}
# with a white label for the black dot
myPlot <- myPlot + annotate("text", x = 9, y = 9, label = "1", color = "white")

#plot and save
plot(myPlot)
ggsave(myPlot, file = "dirichlet.png")


# README: Compare TLP with SCAD and MCP (ncvreg)
library(tictoc)
library(ncvreg)
source("tlpreg.r")
source("cv.tlpreg.r")
source("tlpreg1.r")
source("cv.tlpreg1.r")

set.seed(2020)
n <- 500
p <- 50000
X <- matrix(rnorm(n*p),n,p)
Z <- rnorm(n)
for(j in 1:p) {
  X[,j] <- X[,j] + Z
  X[,j] <- (X[,j] - mean(X[,j])) / sd(X[,j])
}
y <- 1 + 0.5*(X[,1] - X[,2] + X[,10] - X[,50] + X[,200]) + rnorm(n)

# SPEED TEST
tic("SCAD")
m1 <- cv.ncvreg(X=X, y=y, penalty="SCAD")
mm1 <- ncvreg(X=X, y=y, lambda=m1$lambda.min, penalty="SCAD")
toc()

tic("MCP")
m2 <- cv.ncvreg(X=X, y=y, penalty="MCP")
mm2 <- ncvreg(X=X, y=y, lambda=m2$lambda.min, penalty="MCP")
toc()

tic("TLP-Regularized")
m3 <- cv.tlpreg0(X=X, y=y, nfold=10)
mm3 <- tlpreg0(X=X, y=y, gamma=m3$gamma.min)
toc()

tic("L0-Constrained")
m4 <- cv.tlpreg1(X=X, y=y, nfold=10)
mm4 <- tlpreg1(X=X, y=y, K=m4$K.min)
toc()

# ACCURACY TEST
which(mm1$beta[-1]!=0)
which(mm2$beta[-1]!=0)
which(as.numeric(mm3$b)!=0)
which(as.numeric(mm4$b)!=0)

# Note: informative variables are X1, X2, X10, X50, X200


=begin
  # sample-diagonalization01.rb

  require "algebra"
  M = SquareMatrix(Rational, 3)
  a = M[[1,-1,-1], [-1,1,-1], [2,1,-1]]
  puts "A = "; a.display; puts
  #A =
  #  1,  -1,  -1
  # -1,   1,  -1
  #  2,   1,  -1

  e = a.diagonalize

  puts "Charactoristic Poly.: #{e.chpoly} => #{e.facts}";puts
  #Charactoristic Poly.: t^3 - t^2 + t - 6 => (t - 2)(t^2 + t + 3)

  puts "Algebraic Numbers:"
  e.roots.each do |po, rs|
    puts "#{rs.join(', ')} : roots of #{po} == 0"
  end; puts
  #Algebraic Numbers:
  #a, -a - 1 : roots of t^2 + t + 3 == 0

  puts "EigenSpaces: "
  e.evalues.uniq.each do |ev|
    puts "W_{#{ev}} = <#{e.espaces[ev].join(', ')}>"
  end; puts
  #EigenSpaces:
  #W_{2} = <[4, -5, 1]>
  #W_{a} = <[1/3a + 1/3, 1/3a + 1/3, 1]>
  #W_{-a - 1} = <[-1/3a, -1/3a, 1]>

  puts "Trans. Matrix:"
  puts "P ="
  e.tmatrix.display; puts
  puts "P^-1 * A * P = "; (e.tmatrix.inverse * a * e.tmatrix).display; puts
  #P =
  #  4, 1/3a + 1/3, -1/3a
  # -5, 1/3a + 1/3, -1/3a
  #  1,   1,   1
  #
  #P^-1 * A * P =
  #  2,   0,   0
  #  0,   a,   0
  #  0,   0, -a - 1
((<_|CONTENTS>))
=end


##
## DIMENSIONALITY REDUCTION AND CELL PHENOTYPING
##
## This script will load the data and apply linear dimensionality reduction
## analysis (PCA, JIVE, MDS), nonlinear dimensionality reduction analysis (tSNE),
## and cell phenotyping using ensemble clustering (see paper for more details)
##
## date: 07/05/2019

## libraries
source("libraries.R")

##  Data and annotations
source("readData.R")

## ## ## ## ## ## ## ## ## ## ## ## #
#                                   #
#  Linear dimensionality reduction  #
#                                   #
## ## ## ## ## ## ## ## ## ## ## ## #

## Functions to use for plotting linear dimensionality results
source('plotLinDR.r')

## we subsample without loss of generality. set seed for reproducibility
set.seed(123)
subsample <- sample(seq(1:dim(nonrand)[1]),dim(nonrand)[1]/10)

## PCA
pca_nonrand = prcomp(nonrand@exprs[subsample,-excludedMarkers], center = T, scale. = F) # non-randomized
pca_rand.type1 = prcomp(rand.type1@exprs[subsample,-excludedMarkers], center = T, scale. = F) # randomized type 1
pca_rand.type2 = prcomp(rand.type2@exprs[subsample,-excludedMarkers], center = T, scale. = F) # randomized type 2
pca_rand.extreme = prcomp(rand.extreme@exprs[subsample,-excludedMarkers], center = T, scale. = F) # extreme randomization

## how much variance each PC is explaining ?
expVar.type1 = data.frame(nonrand = cumsum(explained.variance(pca_nonrand$sdev)),
                          rand = cumsum(explained.variance(pca_rand.type1$sdev)) )

expVar.type2 = data.frame(nonrand = cumsum(explained.variance(pca_nonrand$sdev)),
                          rand = cumsum(explained.variance(pca_rand.type2$sdev)) )

expVar.extreme = data.frame(nonrand = cumsum(explained.variance(pca_nonrand$sdev)),
                               rand = cumsum(explained.variance(pca_rand.extreme$sdev)) )

## perform JIVE
J.type1 <- r.jive::jive(list(t(nonrand@exprs[subsample,-excludedMarkers]),
                       t(rand.type1@exprs[subsample,-excludedMarkers])),scale = F, center = T, maxiter = 100)

J.type2 <- r.jive::jive(list(t(nonrand@exprs[subsample,-excludedMarkers]),
                       t(rand.type2@exprs[subsample,-excludedMarkers])),scale = F, center = T, maxiter = 100)

J.extreme <- r.jive::jive(list(t(nonrand@exprs[subsample,-excludedMarkers]),
                       t(rand.extreme@exprs[subsample,-excludedMarkers])),scale = F, center = T, maxiter = 100)

## Perform MDS (median marker values)
data.MDS = data.frame( nonrand = apply(exprs(nonrand)[,-excludedMarkers],2,median),
                       type1 = apply(exprs(rand.type1)[,-excludedMarkers],2,median),
                       type2 = apply(exprs(rand.type2)[,-excludedMarkers],2,median),
                       maximal = apply(exprs(rand.extreme)[,-excludedMarkers],2,median))
rownames(data.MDS) = allMarkers$CytkPanel[-excludedMarkers]

mds = limma::plotMDS(data.MDS,plot = FALSE)

ggMDS <- data.frame(MDS1 = mds$x, MDS2 = mds$y, sample_id = colnames(data.MDS),
                    condition = factor(c("Non-Random.",rep("Randomized",3))))

## plot the 2D PCA embeddings
plot.pca(pca_nonrand$x[,1:2],'Non-randomized')
plot.pca(pca_rand.type1$x[,1:2],'Randomized, type 1')
plot.pca(pca_rand.type2$x[,1:2],'Randomized, type 2')
plot.pca(pca_rand.extreme$x[,1:2],'Randomized, extreme')

## plot the explained variance per PC
ggplot(expVar.type1, aes(nonrand, rand)) + geom_point(color = "tomato", alpha = 0.7) +
  labs(x="non-randomized (%)",y="randomized, type 1 (%)") + xlim(c(0,100)) + ylim(c(0,100)) + geom_abline(intercept = 0, lty = 2, size = 0.25)

ggplot(expVar.type2, aes(nonrand, rand)) + geom_point(color = "tomato", alpha = 0.7) +
  labs(x="non-randomized (%)",y="randomized, type 2 (%)") + xlim(c(0,100)) + ylim(c(0,100)) + geom_abline(intercept = 0, lty = 2, size = 0.25)

ggplot(expVar.extreme, aes(nonrand, rand)) + geom_point(color = "tomato", alpha = 0.7) +
  labs(x="non-randomized (%)",y="randomized, extreme (%)") + xlim(c(0,100)) + ylim(c(0,100)) + geom_abline(intercept = 0, lty = 2, size = 0.25)

## plot the common, individual and residual variances
plot.jive(J.type1,titles = c(gsub('\\-','\n','non-randomized'), "randomized, type 1"))
plot.jive(J.type2,titles = c(gsub('\\-','\n','non-randomized'), "randomized, type 2"))
plot.jive(J.extreme,titles = c(gsub('\\-','\n','non-random.'), gsub(' ','\n','extreme')))

## plot the multidimensional scaling difference
plot.MDS(ggMDS)

## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#                                             #
#  Non linear dimensionality reduction (tSNE) #
#                                             #
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##

## Functions to use
source("plotNonLinDR.R")

## Perform tSNE (no subsampling)
set.seed(123)
tsne_out_nonrand <- Rtsne.multicore::Rtsne.multicore(nonrand@exprs[,-excludedMarkers], dims = 2)

set.seed(123)
tsne_out_rand_type1 <- Rtsne.multicore::Rtsne.multicore(rand.type1@exprs[,-excludedMarkers], dims = 2)

set.seed(123)
tsne_out_rand_type2 <- Rtsne.multicore::Rtsne.multicore(rand.type2@exprs[,-excludedMarkers], dims = 2)

set.seed(123)
tsne_out_rand_extreme <- Rtsne.multicore::Rtsne.multicore(rand.extreme@exprs[,-excludedMarkers], dims = 2)

## Plot the tSNE embeddings
plot.tSNE(tsne_out_nonrand$Y,'Non-randomized')
plot.tSNE(tsne_out_rand_type1$Y,'Randomized, type 1')
plot.tSNE(tsne_out_rand_type2$Y,'Randomized, type 2')
plot.tSNE(tsne_out_rand_extreme$Y,'Randomized, extreme')

## Plot the distribution of each marker on the tSNE embedding
tSNE.nonrand <- data.frame(tSNE1 = tsne_out_nonrand$Y[,1],
                           tSNE2 = tsne_out_nonrand$Y[,2],
                           as.matrix(nonrand@exprs[,-excludedMarkers]))

tSNE.rand.type1 <- data.frame(tSNE1 = tsne_out_rand_type1$Y[,1],
                              tSNE2 = tsne_out_rand_type1$Y[,2],
                              as.matrix(rand.type1@exprs[,-excludedMarkers]))

tSNE.rand.type2 <- data.frame(tSNE1 = tsne_out_rand_type2$Y[,1],
                              tSNE2 = tsne_out_rand_type2$Y[,2],
                              as.matrix(rand.type2@exprs[,-excludedMarkers]))

tSNE.rand.extreme <- data.frame(tSNE1 = tsne_out_rand_extreme$Y[,1],
                              tSNE2 = tsne_out_rand_extreme$Y[,2],
                              as.matrix(rand.extreme@exprs[,-excludedMarkers]))

M <- allMarkers[-excludedMarkers,2]
colnames(tSNE.rand.extreme)[3:ncol(tSNE.rand.extreme)] <- colnames(tSNE.rand.type2)[3:ncol(tSNE.rand.type2)] <- colnames(tSNE.rand.type1)[3:ncol(tSNE.rand.type1)] <- colnames(tSNE.nonrand)[3:ncol(tSNE.nonrand)] <- M

nrand_label <- ggdraw() + draw_label("non-rand.", size = 6)
rand_label_type1 <- ggdraw() + draw_label("type 1", size = 6)
rand_label_type2 <- ggdraw() + draw_label("type 2", size = 6)
rand_label_extreme <- ggdraw() + draw_label("maximal", size = 6)

p.all <- list()
for (m in 1:length(M)){

  g1 <- plot.Marker.on.tSNE(tSNE.nonrand[,c(1,2,(2+m))], marker.name = "")
  g2 <- plot.Marker.on.tSNE(tSNE.rand.type1[,c(1,2,(2+m))], marker.name = "")
  g3 <- plot.Marker.on.tSNE(tSNE.rand.type2[,c(1,2,(2+m))], marker.name = "")
  g4 <- plot.Marker.on.tSNE(tSNE.rand.extreme[,c(1,2,(2+m))], marker.name = "")

  marker_label <- ggdraw() + draw_label(M[m], angle = 90, size = 6)

  p1 <- plot_grid(nrand_label,rand_label_type1, rand_label_type2,rand_label_extreme,
                  g1 + theme(legend.position="none",plot.margin=margin(t=-0.5,b=0.1, unit="cm")),
                  g2 + theme(legend.position="none",plot.margin=margin(t=-0.5,b=0.1,unit="cm")),
                  g3 + theme(legend.position="none",plot.margin=margin(t=-0.5,b=0.1,unit="cm")),
                  g4 + theme(legend.position="none",plot.margin=margin(t=-0.5,b=0.1,unit="cm")),
                  nrow = 2, rel_heights = c(.1,1))

  p3 <- plot_grid(marker_label, p1, rel_widths = c(.1,1))

  p.all[[m]] <- p3 + annotate("rect", xmin = 0, xmax = 1, ymin = 0, ymax = 1, color = "gray95", fill = NA)

}
p.all[[m+1]] <- get_legend(g1)

p <- plot_grid(plotlist = p.all, nrow = 8, ncol = 4)
p <- add_sub(p,expression(paste(bold("Supplementary Figure 4")," tSNE analysis results for all markers. Each subplot displays the marker distribution when the")),
             x = 0, y = 0, hjust = 0, vjust = 0, size = 8)
p <- add_sub(p,"non-randomized data (left) and the randomized data are employed",
             x = 0, y = 1, hjust = 0, vjust = 1.3, size = 8)

ggsave(paste0("supplementary_figure4_full.tif"),plot = p,device = "tiff",dpi = 300,width = 20,height = 18, units ="cm")

## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#                                                              #
# Ensemble clustering using SOM (Nowicka et al., F1000, 2017)  #
#                                                              #
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #

## Functions to use
source("ensembleClustFuncs.R")

## Transform the data into a FlowSOM object
nonrand.SOM <- ReadInput('../data/nonrandomized.fcs', transform =FALSE, scale =FALSE)
nonrand.SOM$data[,3:58] <- asinh(nonrand.SOM$data[,3:58]/5) # arcsinh transform

rand.type1.SOM <- ReadInput('../data/randomized_type1.fcs', transform =FALSE, scale =FALSE)
rand.type1.SOM$data[,3:58] <- asinh(rand.type1.SOM$data[,3:58]/5) # arcsinh transform

rand.type2.SOM <- ReadInput('../data/randomized_type2.fcs', transform =FALSE, scale =FALSE)
rand.type2.SOM$data[,3:58] <- asinh(rand.type2.SOM$data[,3:58]/5) # arcsinh transform

rand.extreme.SOM <- ReadInput('../data/randomized_maximal.fcs', transform =FALSE, scale =FALSE)

## Scale marker abundances to values between 0 and 1 (only for visualization)
nonrand01 <- scale01(nonrand.SOM$data)
rand01.type1 <- scale01(rand.type1.SOM$data)
rand01.type2 <- scale01(rand.type2.SOM$data)
rand01.extreme <- scale01(rand.extreme.SOM$data)

## Name the columns with the names of the markers
MarkerNames <- allMarkers$CytkPanel
MarkerNames[c(16,19,26,30,38,45,47)]<-c("CCR6","CD195","CD278","CD194","HLA_DR","CD152","CD279")
colnames(nonrand.SOM$data) <- colnames(nonrand01) <- MarkerNames
colnames(rand.type1.SOM$data) <- colnames(rand01.type1) <- MarkerNames
colnames(rand.type2.SOM$data) <- colnames(rand01.type2) <- MarkerNames
colnames(rand.extreme.SOM$data) <- colnames(rand01.extreme) <- MarkerNames

## Perform Ensemble clustering using SOM
somID.nonrand <- ensemble_clustering_SOM(nonrand.SOM, lineage.Markers, 20, seed = 1)
somID.rand.type1 <- ensemble_clustering_SOM(rand.type1.SOM, lineage.Markers, 20, seed = 1)
somID.rand.type2 <- ensemble_clustering_SOM(rand.type2.SOM, lineage.Markers, 20, seed = 1)
somID.rand.extreme <- ensemble_clustering_SOM(rand.extreme.SOM, lineage.Markers, 20, seed = 1)

## Compare the two clusterings using the F1 measure
FM.type1 <- FMeasure(somID.nonrand,somID.rand.type1)
FM.type2 <- FMeasure(somID.nonrand,somID.rand.type2)
FM.extreme <- FMeasure(somID.nonrand,somID.rand.extreme)

## Compare the two clusterings using the Adjusted Rand Index (0..1)
ARI.type1 <- fossil::adj.rand.index(somID.nonrand,somID.rand.type1)
ARI.type2 <- fossil::adj.rand.index(somID.nonrand,somID.rand.type2)
ARI.extreme <- fossil::adj.rand.index(somID.nonrand,somID.rand.extreme)

## Employ the Hungarian algorithm to find the best matching between the two clusterings
cluster.matches.type1 <- cluster.matches(somID.rand.type1,somID.nonrand)
cluster.matches.type2 <- cluster.matches(somID.rand.type2,somID.nonrand)
cluster.matches.extreme <- cluster.matches(somID.rand.extreme,somID.nonrand)

## Repeat 100 times to check the average discrepancy
metric.100.type1 <- metric100(nonrand.SOM,rand.type1.SOM)
metric.100.type2 <- metric100(nonrand.SOM,rand.type2.SOM)
metric.100.extreme <- metric100(nonrand.SOM,rand.extreme.SOM)

## Create clustering heatmaps
color_clusters <- c("#DC050C", "#FB8072", "#1965B0", "#7BAFDE", "#882E72","#B17BA6", "#FF7F00", "#FDB462", "#E7298A", "#E78AC3",
                    "#33A02C", "#B2DF8A", "#55A1B1", "#8DD3C7", "#A6761D","#E6AB02", "#7570B3", "#BEAED4", "#666666", "#999999")

plot_clustering_heatmap_wrapper(expr = nonrand.SOM$data[, lineage.Markers],expr01 = nonrand01[, lineage.Markers],
                                cell_clustering = somID.nonrand, color_clusters = color_clusters, annot = FALSE)

plot_clustering_heatmap_wrapper(expr = rand.type1.SOM$data[, lineage.Markers],expr01 = rand01.type1[, lineage.Markers],
                                cell_clustering = cluster.matches.type1[somID.rand.type1], color_clusters = color_clusters, annot = FALSE)

plot_clustering_heatmap_wrapper(expr = rand.type2.SOM$data[, lineage.Markers],expr01 = rand01.type1[, lineage.Markers],
                                cell_clustering = cluster.matches.type2[somID.rand.type2], color_clusters = color_clusters, annot = FALSE)

plot_clustering_heatmap_wrapper(expr = rand.extreme.SOM$data[, lineage.Markers],expr01 = rand01.type1[, lineage.Markers],
                                cell_clustering = cluster.matches.extreme[somID.rand.extreme], color_clusters = color_clusters, annot = FALSE)

## Plot the Clusters on the tSNE map (run tSNE in previous section before this one)
SOM.nonrand <- data.frame(tSNE1 = tsne_out_nonrand$Y[,1],
                          tSNE2 = tsne_out_nonrand$Y[,2],
                          nonrand.SOM$data[, lineage.Markers],
                          clusterID = factor(somID.nonrand, levels = 1:20))

SOM.rand.type1 <- data.frame(tSNE1 = tsne_out_rand_type1$Y[,1],
                             tSNE2 = tsne_out_rand_type1$Y[,2],
                             rand.type1.SOM$data[, lineage.Markers],
                             clusterID = factor(somID.rand.type1, levels = 1:20))

SOM.rand.type2 <- data.frame(tSNE1 = tsne_out_rand_type2$Y[,1],
                             tSNE2 = tsne_out_rand_type2$Y[,2],
                             rand.type2.SOM$data[, lineage.Markers],
                             clusterID = factor(somID.rand.type2, levels = 1:20))

SOM.rand.extreme <- data.frame(tSNE1 = tsne_out_rand_extreme$Y[,1],
                               tSNE2 = tsne_out_rand_extreme$Y[,2],
                               rand.extreme.SOM$data[, lineage.Markers],
                               clusterID = factor(somID.rand.extreme, levels = 1:20))

ggplot(SOM.nonrand,  aes(x = tSNE1, y = tSNE2, color = clusterID)) +
  geom_point(size = 0.1, shape = 20) + theme_bw() + scale_color_manual(values = color_clusters[1:20]) +
  guides(color = guide_legend(override.aes = list(size =4), ncol =2))

# don't forget to match the colors before ploting the next figures
ggplot(SOM.rand.type1, aes(x = tSNE1, y = tSNE2, color = clusterID)) +
  geom_point(size = 0.1, shape = 20) + theme_bw() + scale_color_manual(values = color_clusters[cluster.matches.type1]) +
  guides(color = guide_legend(override.aes = list(size =4), ncol =2))

ggplot(SOM.rand.type2, aes(x = tSNE1, y = tSNE2, color = clusterID)) +
  geom_point(size = 0.1, shape = 20) + theme_bw() + scale_color_manual(values = color_clusters[cluster.matches.type2]) +
  guides(color = guide_legend(override.aes = list(size =4), ncol =2))

ggplot(SOM.rand.extreme, aes(x = tSNE1, y = tSNE2, color = clusterID)) +
  geom_point(size = 0.1, shape = 20) + theme_bw() + scale_color_manual(values = color_clusters[cluster.matches.extreme]) +
  guides(color = guide_legend(override.aes = list(size =4), ncol =2))

dimensionality reduction and phenotyping/completeAnalysis.r


library(pbdPAPI)

### Reimplementation of PAPI's FlopsInnerProduct.m in R

n <- 50

x <- matrix(rnorm(n), n, 1)
y <- matrix(rnorm(n), n, 1)

op <- expression(crossprod(x,y))

report <- system.flops(eval(op))
count <- report$flpops
theoretical <- 2*n
mflops <- report$mflops

data.frame(n=n, measured=count, theoretical=theoretical, difference=count-theoretical, "pct.error"=(1.0 - (theoretical/count))*100, mflops=mflops)


f <- function(x) (x + 3)^2
f <- Vectorize(f)
lf <- function(x) log(f(x))
lf <- Vectorize(lf)

lf_prime_num <- function(x) numDeriv::grad(lf, x)

lf_prime_analytical <- function(x) (2*(x+3))/f(x)

curve(lf_prime_num(x), 0, 10)
curve(lf_prime_analytical(x), 0 , 10, lwd = 2, lty = 2, col = 2, add = TRUE)


suppressPackageStartupMessages(library(float))
set.seed(1234)

tol = 1e-6

x = crossprod(matrix(stats::rnorm(30), 10))
xs = fl(x)

test = dbl(chol2inv(chol(xs)))
truth = chol2inv(chol(x))
stopifnot(all.equal(test, truth, tol=tol))


horner <- function(a, x) {
  iv <- 0
  for(i in length(a):1) {
    iv <- iv * x + a[i]
  }
  iv
}

cat(horner(c(-19, 7, -4, 6), 3), "\n")


#!/bin/Rscript

library(DAAG)
library(ggplot2)
data(progression)

# display the log log plot of time vs distance
plot(log(Time) ~ log(Distance), data=progression)

# display the log log plot of time vs distance with a simple linear
# regression using only points
xyplot(log(Time) ~ log(Distance), data=progression, type=c("p","r"))

# display the log log plot of time vs distance with a LOESS fit
# regression using only points
xyplot(log(Time) ~ log(Distance), data=progression,
    type=c("p","smooth"))

# display the residuals from the linear model for each value on
# a log plot of the distance
res <- resid(lm(log(Time) ~ log(Distance), data=progression))
plot(res ~ log(Distance), data=progression,
    ylab="Residuals from regression line on log scales")

# display the progression of record times for each individual event vs year
distlist <- c(0.1, 0.2, 0.4, 0.8, 1.5,  1.6093, 3, 10, 42.195)
for (d in distlist){

    # get a sorted matrix of each event to search for anomalies
    newdata <- subset(progression, Distance == d, select=c(year, Time))
    Time <- newdata[['Time']][order(newdata[['year']])]
    year <- sort(newdata[['year']])
    anomalies <- matrix(, nrow=length(Time), ncol=2, dimnames=list(NULL, c("year", "Time")))

    # look for times that are slower than previous records
    index <- 1
    for (i in 2:length(Time)){
        if (Time[i] > Time[i-1] && year[i] > year[i-1]){
            anomalies[index,] <- c(year[i], Time[i])
            index <- index + 1
        }
    }

    # create the base plt
    p <- ggplot(data=newdata, aes(x=year, y=Time, group=1)) +
         geom_point() +
         stat_smooth(method="lm",formula=y~log(x),fill="red") +
         ggtitle(paste(toString(d)," km"))

    # if there are anomalies, add them to the plot
    if (!is.na(anomalies[1,1])){
        dframe <- as.data.frame(anomalies)
        pts <- geom_point(data=dframe, colour="red", size = 3)
        p <- p + pts
    }
    print(p)
}


# Util

standard_error <- function(X, y, robust){
    if (robust %in% c("White", "white", "HC0")) {
        std_error <- robust_stde0(X, y)
        cov_type <- "heteroskadestic (White)"
    } else if (robust %in% c("Hinkley", "hinkley", "HC1")) {
        std_error <- robust_stde1(X, y)
        cov_type <- "heteroskadestic (Hinkley)"
    } else if (robust %in% c("Horn", "horn", "HC2")) {
        std_error <- robust_stde2(X, y)
        cov_type <- "heteroskadestic (Horn)"
    } else if (robust %in% c("MacKinnon", "mackinnon", "HC3")) {
        std_error <- robust_stde3(X, y)
        cov_type <- "heteroskadestic (MacKinnon)"
    } else {
        std_error <- stde(X, y)
        cov_type <- "homoskadestic"
    }
    return(list("value"=std_error, "cov_type"=cov_type))
}

# Formula

#' @export
homoskedastic_standard_error <- function(X, y){
    diag(homoskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
white_heteroskedastic_standard_error <- function(X, y){
    diag(white_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
hinkley_heteroskedastic_standard_error <- function(X, y){
    diag(hinkley_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
horn_heteroskedastic_standard_error <- function(X, y){
    diag(horn_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
mackinnon_heteroskedastic_standard_error <- function(X, y){
    diag(mackinnon_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

# Abbreviation

#' @export
stde <- homoskedastic_standard_error

#' @export
robust_stde0 <- white_heteroskedastic_standard_error

#' @export
robust_stde1 <- hinkley_heteroskedastic_standard_error

#' @export
robust_stde2 <- horn_heteroskedastic_standard_error

#' @export
robust_stde3 <- mackinnon_heteroskedastic_standard_error


png("#49_custom_pie_plot.png" , width = 480, height = 480 )

#Data

x <- c(15, 9, 75, 90, 1, 1, 11, 5, 9, 8, 33, 11, 11, 20, 14, 13, 10, 28, 33, 21, 24, 25, 11, 33)

#Fonction clock plot
clock.plot <- function (x, col = rainbow(n), ...) {
  if( min(x)<0 ) x <- x - min(x)
  if( max(x)>1 ) x <- x/max(x)
  n <- length(x)
  if(is.null(names(x))) names(x) <- 0:(n-1)
  m <- 1.05
  plot(0,
       type = 'n', # do not plot anything
       xlim = c(-m,m), ylim = c(-m,m),
       axes = F, xlab = '', ylab = '', ...)
  a <- pi/2 - 2*pi/200*0:200
  polygon( cos(a), sin(a) )
  v <- .02
  a <- pi/2 - 2*pi/n*0:n
  segments( (1+v)*cos(a), (1+v)*sin(a),
            (1-v)*cos(a), (1-v)*sin(a) )
  segments( cos(a), sin(a),
            0, 0,
            col = 'light grey', lty = 3)
  ca <- -2*pi/n*(0:50)/50
  for (i in 1:n) {
    a <- pi/2 - 2*pi/n*(i-1)
    b <- pi/2 - 2*pi/n*i
    polygon( c(0, x[i]*cos(a+ca), 0),
             c(0, x[i]*sin(a+ca), 0),
             col=col[i] )
    v <- .1
    text((1+v)*cos(a), (1+v)*sin(a), names(x)[i])
  }
}
clock.plot(x,
  main = "Number of visitors to a web site for each hour of the day")

dev.off()