Description

The simulated concentration-time profiles are represented by a solid black line to represent the median (typical) patient at steady state, with the shaded light blue area representing the 95% prediction interval of 100 patients simulated. The drug, amount and frequency of dosing can be changed in the left panel

Description

The simulated concentration-time profiles are shown by a solid black line and represent a median (typical) patient. Patient adherence can be changed and results in random missed days in the dosing schedule. A 30 day simulation is performed and the graph below can be used to zoom in on specific days. The drug, amount and frequency of dosing can be changed in the left panel
Show concentration profiles for day #:

About

Welcome to the UCSF TB-Lesion tool developed by Savic Labs in support of the CPTR program funded by the Bill and Melinda Gates Foundation. This tool allows simulations of the time course of drug concentrations in specific lesions during drug treatment of TB. All simulations are based on a non-linear mixed effects model based on data from clinical trial NCT00816426. More information on the methods used are available at http://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1002773

Some notes on use of this app:

1. Interfaces for Patient PK and Lesion PK is provided and can be switched from the left menu.

2. The Patient PK tab allows for simulation of different drug dosing in two patients, one with cavity and one without to compare their expected PK.

3. The Lesion PK tab simulates PK profiles for each individual lesion over 30 days.

4. The Patient Adherence tab simulates random patterns of adherence and its effect on steady-state levels.

5. The Multi-Drug comparison tab simulates drug onboard windows for multiple drugs as a percentage of coverage.

Please note that this tool is a research tool for TB experts. Do not use this tool to inform individual treatment decisions.

Description

Two steady state scenarios are shown for a patient that has no caseous lesions and a patient that does. The solid black line represents the median (typical) patient and the red line represents a patient with lower exposure according to the determined population variability of the selected drug. The drug, amount and frequency of dosing can be changed in the left panel

Patient and Therapy Settings

Patient without cavity

Exposure

Patient with cavity

Exposure

Description

The number of drugs above MIC over time at steady state over a 24h dosing interval are shown as colored blocks of an ideal drug present grid. Each colored block represents one hour that a drug is above the MIC. The drugs are stacked for each hour with different colors representing the drugs selected in their respective panels. Empty squares show no drug on board and the resulting percentage coverage of the grid is displayed below the lesion name. A typical and low exposure patient's coverage shown in the different tabs

Drug 1

Drug 2

Drug 3

Drug 4

Lesion Pharmacokinetics

Acknowledgements

We are grateful to the subjects who enrolled in the study; Y. Kim, M.S. Kong, Y. Cai, J. Gonzales and L. Goldfeder; and the clinical teams at the three Korean centers (Asan Medical Centre, Pusan National University Hospital, and the National Medical Center) for their efforts in making the study a success.
This work was carried out with funding from US National Institutes of Health (NIH) grants R01AI106398-01 and R01AI111967, grant OPP1066499 from the Bill and Melinda Gates Foundation, the Intramural Research Program of the NIH National Institute of Allergy and Infectious Diseases (C.E.B.), the Critical Path to TB Drug Regimens (CPTR) Initiative, Bill and Melinda Gates Foundation, grants OPP1031105 and Grand Challenges in Global Health-11, and funding from the Korean Centers for Disease Control of the Korean Ministry of Health and Welfare to the International Tuberculosis Research Center.
We would also like to thank Klaus Romero and Alexander Berg from the Critical Path to TB Drug Regimens Initiative (CPTR) for their valuable discussion and support throughout this project.

Citation

Full methodology and results of this project was published in PLOS Medicine .
The paper is freely available for anyone to read, download, and distribute.
To cite any of the results or code used from this website, please cite the original paper;
Strydom N, Gupta SV, Fox WS, Via LE, Bang H, Lee M, et al. (2019) Tuberculosis drugs’ distribution and emergence of resistance in patient’s lung lesions: A mechanistic model and tool for regimen and dose optimization. PLoS Med 16(4): e1002773. https://doi.org/10.1371/journal. pmed.1002773

model.txt

                            
                            ; l =  Lung, l2 = Necrotic Nodule, l3 = Closed nodule caseum
                            ; l4 = caseous fibrotic, l5 = cavity caseum
                            ; l6 = cavity wall,  l7 = fibrotic tissue
                            ;l8 = small nodule, l9 = fungal ball
                            
                            
                            [LONGITUDINAL]
                            input = {
                            ka, Cl, V, Q2, V2, tg,
                            
                            kpl2, rpl2,
                            kpl1, rpl1,
                            kpl3, rpl3,
                            kpl4, rpl4,
                            kpl5, rpl5,
                            kpl6, rpl6,
                            kpl7, rpl7,
                            kpl8, rpl8,
                            kpl9, rpl9,
                            
                            bc, ac,
                            b1, b2, b3, b4, b5, b6, b7, b8, b9}
                            
                            PK :
                            
                            depot(type = 1, target = Ad, Tlag = tg)
                            
                            
                            EQUATION:
                            ; ODE's for all compartments
                            
                            ddt_Ad = -ka * Ad
                            ddt_Ac = ka * Ad - Cl * Ac/V - Q2 * (Ac/V - Ap/V2)
                            ddt_Ap = Q2 * (Ac/V - Ap/V2)
                            ddt_Al1 = kpl1 * ((rpl1*Ac/V) - Al1)
                            ddt_Al2 = kpl2 * ((rpl2*Ac/V) - Al2)
                            ddt_Al3 = kpl3 * ((rpl3*Ac/V) - Al3)
                            ddt_Al4 = kpl4 * ((rpl4*Ac/V) - Al4)
                            ddt_Al5 = kpl5 * ((rpl5*Ac/V) - Al5)
                            ddt_Al6 = kpl6 * ((rpl6*Ac/V) - Al6)
                            ddt_Al7 = kpl7 * ((rpl7*Ac/V) - Al7)
                            ddt_Al8 = kpl8 * ((rpl8*Ac/V) - Al8)
                            ddt_Al9 = kpl9 * ((rpl9*Ac/V) - Al9)
                            
                            ; check if AUC output matches with function
                            
                            ddt_CcAUC = Ac
                            ddt_L1AUC = Al1     
                            ddt_L2AUC = Al2  
                            ddt_L3AUC = Al3 
                            ddt_L4AUC = Al4 
                            ddt_L5AUC = Al5 
                            ddt_L6AUC = Al6 
                            ddt_L7AUC = Al7 
                            ddt_L8AUC = Al8 
                            ddt_L9AUC = Al9                        
                            

                            ; Plasma concentrations
                            
                            Cc = Ac/V
                            
                            ; Lesion concentrations
                            
                            L1 = Al1
                            L2 = Al2
                            L3 = Al3
                            L4 = Al4
                            L5 = Al5
                            L6 = Al6
                            L7 = Al7
                            L8 = Al8
                            L9 = Al9
                            
                            CcA = CcAUC
                            L1A = L1AUC
                            L2A = L2AUC
                            L3A = L3AUC
                            L4A = L4AUC
                            L5A = L5AUC
                            L6A = L6AUC
                            L7A = L7AUC
                            L8A = L8AUC
                            L9A = L9AUC

                            
                            ; Error model
                            
                            gcp = bc * Cc      ; proportional error on plasma concentration
                            gca = ac + Cc      ; additive error on plasma concentration
                            g1 = b1 * L1       ; proportional error on L1 concentration
                            g2 = b2 * L2       ; proportional error on L2 concentration
                            g3 = b3 * L3       ; proportional error on L3 concentration
                            g4 = b4 * L4       ; proportional error on L4 concentration
                            g5 = b5 * L5       ; proportional error on L5 concentration
                            g6 = b6 * L6       ; proportional error on L6 concentration
                            g7 = b7 * L7       ; proportional error on L7 concentration
                            g8 = b8 * L8       ; proportional error on L8 concentration
                            g9 = b9 * L9       ; proportional error on L9 concentration
                            
                            
                            
                            DEFINITION:
                            
                            y1 = {distribution = normal, prediction = Cc, sd = gcp}
                            y2 = {distribution = normal, prediction = Cc, sd = gca}
                            y3 = {distribution = normal, prediction = L1, sd = g1}
                            y4 = {distribution = normal, prediction = L2, sd = g2}
                            y5 = {distribution = normal, prediction = L3, sd = g3}
                            y6 = {distribution = normal, prediction = L4, sd = g4}
                            y7 = {distribution = normal, prediction = L5, sd = g5}
                            y8 = {distribution = normal, prediction = L6, sd = g6}
                            y9 = {distribution = normal, prediction = L7, sd = g7}
                            y10 = {distribution = normal, prediction = L8, sd = g8}
                            y11 = {distribution = normal, prediction = L9, sd = g9}
                            
                            
                            [INDIVIDUAL]
                            input={
                            ka_pop, omega_ka,
                            Cl_pop, omega_Cl, 
                            V_pop, omega_V,
                            Q2_pop, omega_Q2,
                            V2_pop, omega_V2,
                            tg_pop, omega_tg,
                            rpl1_pop, omega_rpl1, 
                            rpl2_pop, omega_rpl2, 
                            rpl3_pop, omega_rpl3, 
                            rpl4_pop, omega_rpl4, 
                            rpl5_pop, omega_rpl5, 
                            rpl6_pop, omega_rpl6, 
                            rpl7_pop, omega_rpl7, 
                            rpl8_pop, omega_rpl8, 
                            rpl9_pop, omega_rpl9}
                            
                            DEFINITION:
                            ;Omega
                            ka = {distribution = lognormal, prediction = ka_pop, sd = omega_ka}
                            Cl = {distribution = lognormal, prediction = Cl_pop, sd = omega_Cl}
                            V = {distribution = lognormal, prediction = V_pop, sd= omega_V}
                            Q2 = {distribution = lognormal, prediction = Q2_pop, sd = omega_Q2}
                            V2 = {distribution = lognormal, prediction = V2_pop, sd = omega_V2}
                            tg = {distribution = lognormal, prediction = tg_pop, sd = omega_tg}
                            rpl1 = {distribution = lognormal, prediction = rpl1_pop, sd = omega_rpl1}
                            rpl2 = {distribution = lognormal, prediction = rpl2_pop, sd = omega_rpl2}
                            rpl3 = {distribution = lognormal, prediction = rpl3_pop, sd = omega_rpl3}
                            rpl4 = {distribution = lognormal, prediction = rpl4_pop, sd = omega_rpl4}
                            rpl5 = {distribution = lognormal, prediction = rpl5_pop, sd = omega_rpl5}
                            rpl6 = {distribution = lognormal, prediction = rpl6_pop, sd = omega_rpl6}
                            rpl7 = {distribution = lognormal, prediction = rpl7_pop, sd = omega_rpl7}
                            rpl8 = {distribution = lognormal, prediction = rpl8_pop, sd = omega_rpl8}
                            rpl9 = {distribution = lognormal, prediction = rpl9_pop, sd = omega_rpl9}
                            

ui.R

#Libraries-------

library(shinydashboard)

#Sidebar---------
sidebar <- dashboardSidebar(
  hr(),
  
  sidebarMenu(
    id="tabs",
    menuItem("About", tabName = "about", icon = icon("graduation-cap")),
    menuItem("Patient PK", tabName = "summary", icon = icon("user"), selected = TRUE),
    menuItem("All lesions", tabName = "plot", icon = icon("area-chart")),
    menuItem("Patient Adherence", tabName = "Adh", icon = icon("calendar")),
    menuItem("Multi-drug comparison", tabName = "Multi", icon = icon("align-center")),
    menuItem("Acknowledgements", tabName = "Ack", icon = icon("handshake")),
    menuItem("Citation", tabName = "Cite", icon = icon("link")),
    menuItem("Codes",  icon = icon("file-text-o"),
      menuSubItem("Parameters", tabName = "params", icon = icon("angle-right")),
      menuSubItem("Mlxtran", tabName = "mlxtran", icon = icon("angle-right")),
      menuSubItem("ui.R", tabName = "ui", icon = icon("angle-right")),
      menuSubItem("server.R", tabName = "server", icon = icon("angle-right")))
  ),

hr(),
fluidRow(               
column(1),
column(9,

fluidRow(
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "boxes.css")
  ),
  tags$style(type="text/css",
             ".shiny-output-error { visibility: hidden; }",
             ".shiny-output-error:before { visibility: hidden; }"
  )
),
hr(),
radioButtons("ilog", "scale", c("linear" = FALSE,"log" = TRUE), inline=TRUE),
radioButtons("yaxis", "y-axis", c("fixed" = 'fixed', "free" = "free_y"), inline=TRUE),
br()
)
),   

hr()
)

#Body-----
##Lesion PK------
body <- dashboardBody(
tabItems(
tabItem(tabName = "plot",
fluidRow( 
  box(title = "Description", width = 12, collapsible = T, "The simulated concentration-time profiles are represented by a solid black line to represent the median (typical) patient at steady state, with the shaded light blue area representing the 95% prediction interval of 100 patients simulated. The drug, amount and frequency of dosing can be changed in the left panel", 
      collapsed = T, status = 'primary', solidHeader = T, footer = a("https://doi.org/10.1371/journal.         pmed.1002773", href="https://doi.org/10.1371/journal.         pmed.1002773")),
  selectInput("lesion", label = "Lesion summary", choices = c('Plasma', 'Lung', 'Cavity wall','Small nodule','Caseum from cavity','Closed nodule caseum','Caseous fibrotic nodule','Necrotic nodule', 'Fibrotic tissue', 'Fungal ball')),
  # AUC valueBox
  infoBoxOutput("aucBox"),
  
  # Cmax valueBox
  infoBoxOutput("cmaxBox"),
  
  # Time below MIC valueBox
  infoBoxOutput("tmicBox"),
  
  box(width = 3,    height=750,
                           selectInput("Drug", label = "Drug", choices = c('RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD')),
                           
                           numericInput("amount1",label="Amount (mg)", value=600),
                           numericInput("ii1", label="Dosing interval (hrs)",value=24),
                           numericInput("mic1", label="MIC (mg/L)",value=1)
                           
  ),
  box(width = 9,   height=750,
      #tags$head(tags$style(".rightAlign{float:right;}")),
      #"Show concentration profiles for day #:",
      #plotOutput("timePlot", height = 40),
      #box(sliderInput("day1", label = '',value=30, min = 0, max = 30, step = 1), width = "100%"),
      plotOutput("lesion_plot", height = 750)
      
)
)
),

##Adherence PK------

tabItem(tabName = "Adh",
        box(title = "Description", width = 12, collapsible = T, "The simulated concentration-time profiles are shown by a solid black line and represent a median (typical) patient.
        Patient adherence can be changed and results in random missed days in the dosing schedule. A 30 day simulation is performed and the graph below can be used to zoom in on specific days. The drug, amount and frequency of dosing can be changed in the left panel", collapsed = T, status = 'primary', solidHeader = T, footer = a("https://doi.org/10.1371/journal.         pmed.1002773", href="https://doi.org/10.1371/journal.         pmed.1002773")),
        fluidRow( 
          tags$style(HTML(".js-irs-1 .irs-single, .js-irs-1 .irs-bar-edge, .js-irs-1 .irs-bar {background: none; border-top: none ;
                              border-bottom: none ;}")),
          
          box(width = 3,    height=750,
              selectInput("Drug1", label = "Drug", choices = c('RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD')),
              numericInput("amount_Adh",label="Amount (mg)",value=600),
              numericInput("ii_Adh", label="Dosing interval (hrs)",value=24),
              numericInput("mic_Adh", label="MIC (mg/L)",value=1),
              sliderInput("adh1", label="% Adherence",value=90, min = 10, max = 100, step = 10)
              
              
          ),
          box(width = 9,   height=750,
              tags$head(tags$style(".rightAlign{float:right;}")),
              "Show concentration profiles for day #:",
              plotOutput("timePlot", height = 40),
              box(sliderInput("day1", label = '',value=1, min = 0, max = 30, step = 1), width = "100%"),
              plotOutput("Adh_plot", height = 520)
              
          )
        )
),

##About Section------

tabItem(tabName = "about",
        box( width = 4,collapsible = FALSE, solidHeader = TRUE, title="About",                
             includeHTML("about.html")
        ),
        box(height=600,collapsible = FALSE,width=8,imageOutput("myImage")
        )
),


##Patient PK------

tabItem(tabName = "summary",
        box(title = "Description", width = 12, collapsible = T, "Two steady state scenarios are shown for a patient that has no caseous lesions and a patient that does. The solid black line represents the median (typical) patient and the red line represents a patient with lower exposure according to the determined population variability of the selected drug. The drug, amount and frequency of dosing can be changed in the left panel", 
         collapsed = T, status = 'primary', solidHeader = T, footer = a("https://doi.org/10.1371/journal.pmed.1002773", href="https://doi.org/10.1371/journal.pmed.1002773")),
        box(title = "Patient and Therapy Settings", status = 'primary', width = 2, height = 600, 
            checkboxGroupInput("percentile", label = "Patient profile for exposure", 
                               choiceNames = list(HTML('<span class="foo black"></span>Typical exposure'), 
                                                  HTML('<span class="foo red"></span>Low exposure')), 
                               choiceValues = c('Typical exposure', 'Low exposure'),
                               selected=c('Typical exposure', 'Low exposure'),inline = F), 
            selectInput("adh2", label="Missed doses", choices = c('0' = 696, '1' = 672, '2' = 648)),
            selectInput("Drug2", label = "Drug", choices = c('RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD')),
            selectInput("amount2", "Amount (mg)", c("600" = 600.0001,"900" = 900, "1200" = 1200), 
                        selected = "600"),
            radioButtons("ii2", "Frequency", c("Daily" = 24, "Twice Daily" = 12), inline=FALSE),
            numericInput("mic2", label = "MIC (mg/L)",value=1)
        ),
        
        
        box(title = 'Patient without cavity', width = 5, height = 600, solidHeader = TRUE, status = 'warning', plotOutput("plot2", height = 300),box(title = 'Exposure', 
                                                                                                                                          #htmlOutput('lung'),
                                                                                                                                          tableOutput('table2'), 
                                                                                                                                          width = 50, status = "warning")), 
        
        box(title = 'Patient with cavity', width = 5, height = 600, solidHeader = TRUE, status = 'danger', plotOutput("plot3", height = 300), box(title = 'Exposure', 
                                                                                                                                            #htmlOutput('cavity'),
                                                                                                                                            tableOutput('table3'), 
                                                                                                                                            width = 50, status = "danger")) 

),

##Multi Drug Comparison------
tabItem(tabName = "Multi",
        fluidRow(
          box(title = "Description", width = 12, collapsible = T, "The number of drugs above MIC over time at steady state over a 24h dosing interval are shown as colored blocks of an ideal drug present grid. Each colored block represents one hour that a drug is above the MIC. The drugs are stacked for each hour with different colors representing the drugs selected in their respective panels. Empty squares show no drug on board and the resulting percentage coverage of the grid is displayed below the lesion name. A typical and low exposure patient's coverage shown in the different tabs", collapsed = T, status = 'primary', solidHeader = T, footer = a("https://doi.org/10.1371/journal.         pmed.1002773", href="https://doi.org/10.1371/journal.         pmed.1002773")),
        box(title = "Drug 1", status = "danger", solidHeader = TRUE, width = 2, height = 400, 
            selectInput("Multi_Drug1", label = "Drug", choices = c('None', 'RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD'), 
                        selected = 'RIF'),
            selectInput("Multi_amount1", "Amount (mg)", c(600,900,1200), 
                        selected = 600),
            radioButtons("Multi_ii1", "Frequency", c("Daily" = 24, "Twice Daily" = 12), inline=T),
            numericInput("Multi_mic1", label="MIC (mg/L)",value=1)
        ),
        box(title = "Drug 2", width = 2, height = 400,#background = "black", 
            selectInput("Multi_Drug2", label = "Drug", choices = c('None', 'RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD'), 
                        selected = 'INH'),
            selectInput("Multi_amount2", "Amount (mg)", c(300,600,900), 
                        selected = 300),
            radioButtons("Multi_ii2", "Frequency", c("Daily" = 24, "Twice Daily" = 12), inline=T),
            numericInput("Multi_mic2", label="MIC (mg/L)",value=0.1)
        ),
        box(title = "Drug 3", status = "primary",solidHeader = TRUE, width = 2, height = 400, 
            selectInput("Multi_Drug3", label = "Drug", choices = c('None', 'RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD'), 
                        selected = 'PZA'),
            selectInput("Multi_amount3", "Amount (mg)", c(1500,3000,4500), 
                        selected = 600),
            radioButtons("Multi_ii3", "Frequency", c("Daily" = 24, "Twice Daily" = 12), inline=T),
            numericInput("Multi_mic3", label="MIC (mg/L)",value=12.5)
        ),
        box(title = "Drug 4", status = "warning",solidHeader = TRUE, width = 2, height = 400, 
            selectInput("Multi_Drug4", label = "Drug", choices = c('None', 'RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD'), 
                        selected = 'None'),
            selectInput("Multi_amount4", "Amount (mg)", c(0), 
                        selected = 0),
            radioButtons("Multi_ii4", "Frequency", c("Daily" = 24, "Twice Daily" = 12), inline=T),
            numericInput("Multi_mic4", label="MIC (mg/L)",value=0)
        ),
        box(title = "Lesion Pharmacokinetics", solidHeader = TRUE, width = 4, height = 400, 
            selectInput("Multi_Drug5", label = "Drug", choices = c('Drug 1', 'Drug 2', 'Drug 3', 'Drug 4'), selected = 'Drug 1'),
            checkboxInput("legend", label = "Legend", value = T),
            plotOutput("LesionPK")
        ),
        
        
        tabBox(tabPanel(title = "Typical", plotOutput("multiFacet1")),
               tabPanel(title = 'Low exposure', plotOutput('multiFacet2')), height = 600, width = 12)
        
)
),

##Acknowledgement Section------

tabItem(tabName = "Ack",
        box( width = 12,collapsible = FALSE, solidHeader = TRUE, title="Acknowledgements",   
        "We are grateful to the subjects who enrolled in the study; Y. Kim, M.S. Kong, Y. Cai, J. Gonzales and L. Goldfeder; and the clinical teams at the three Korean centers (Asan Medical Centre, Pusan National University Hospital, and the National Medical Center) for their efforts in making the study a success.",
        br(),
        "This work was carried out with funding from US National Institutes of Health (NIH) grants R01AI106398-01 and R01AI111967, grant OPP1066499 from the Bill and Melinda Gates Foundation, the Intramural Research Program of the NIH National Institute of Allergy and Infectious Diseases (C.E.B.), the Critical Path to TB Drug Regimens (CPTR) Initiative, Bill and Melinda Gates Foundation, grants OPP1031105 and Grand Challenges in Global Health-11, and funding from the Korean Centers for Disease Control of the Korean Ministry of Health and Welfare to the International Tuberculosis Research Center.",
        br(),
        "We would also like to thank Klaus Romero and Alexander Berg from the Critical Path to TB Drug Regimens Initiative (CPTR) for their valuable discussion and support throughout this project.")
),

##Citation Section------

tabItem(tabName = "Cite",
        box( width = 12,collapsible = FALSE, solidHeader = TRUE, title="Citation",                
        "Full methodology and results of this project was published in ",
        a("PLOS Medicine", href="http://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1002773"),".",
        br(),
        "The paper is freely available for anyone to read, download, and distribute.",
        br(),
        "To cite any of the results or code used from this website, please cite the original paper;",
        br(),
        "Strydom N, Gupta SV, Fox WS, Via LE,
        Bang H, Lee M, et al. (2019) Tuberculosis drugs’
        distribution and emergence of resistance in
        patient’s lung lesions: A mechanistic model and
        tool for regimen and dose optimization. PLoS Med
        16(4): e1002773.",
        a("https://doi.org/10.1371/journal.
        pmed.1002773", href="https://doi.org/10.1371/journal.
        pmed.1002773")
        )
),

##General item tabs------

tabItem(tabName = "params",
        box(solidHeader = TRUE, title="",                
             tableOutput('tbl1')
        )
),
tabItem(tabName = "mlxtran",
        box( width = NULL, solidHeader = TRUE, title="model.txt",                
             pre(includeText("model.txt"))
        )
),
tabItem(tabName = "ui",
box( width = NULL, solidHeader = TRUE, title="ui.R",
pre(includeText("ui.R"))
)
),
tabItem(tabName = "server",
box( width = NULL, solidHeader = TRUE, title="server.R",
pre(includeText("server.R"))
)
)
)

)

dashboardPage(
dashboardHeader(title = "TB Lesions"),
sidebar,
body
)

server.R

library("mlxR")
library("ggplot2")
library("gridExtra")
library("tidyr")
library("dplyr")
library("NonCompart")
library("ggthemes")

simOutput1 <- list(name = c('Cc', 'L1', 'L2', 'L3', 'L4', #Steady state
              'L5', 'L6', 'L7', 'L8', 'L9'), 
     time = seq(0, 744, by = 1))
simOutput1 <- list(simOutput1)

simOutput2 <- list(name = c('Cc', 'L1', 'L2', 'L3', 'L4', #Steady state
                    'L5', 'L6', 'L7', 'L8', 'L9'), 
           time = seq(720, 744, by = 1))
simOutput2 <- list(simOutput2)


#Drug parameters--------
RIF <- readRDS('RIF.rds')
INH <- readRDS('INH.rds')
MFX <- readRDS('MFX.rds')
CFZ <- readRDS('CFZ.rds')
KAN <- readRDS('KAN.rds')
LZD <- readRDS('LZD.rds')
PZA <- readRDS('PZA.rds')
None <- readRDS('None.rds')
noneDataset <- read.csv('noneDataset.csv')

porterfield <- c('#ca222c',
                 '#484848',
                 '#22a6d6',
                 '#ffca63',
                 '#f6a192',
                 '#f6b092',
                 '#f6d992')

drug_choice<<-"RIF"
drug_choice1<<-"RIF"
drug_choice2<<-"RIF"
drug_choice3<<-"RIF"
drug_choice4<<-"INH"
drug_choice5<<-"PZA"
drug_choice6<<-"None"

server <- function(input, output,session) {

#Simulations for cavity and lung----  
  res1 <- reactive({
    #print(p)
    if(drug_choice2!=input$Drug2){
      print("diff")
      updateSelectInput(session, "amount2", choices = dose_info$Dose[dose_info$Drug == input$Drug2],
                        selected = dose_info$Dose[dose_info$Drug == input$Drug2][1])
      updateNumericInput(session,"mic2", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Drug2][1])
      dose_use<-input$amount2
      assign("drug_choice2", input$Drug2, envir = .GlobalEnv)
    }else{
      print("same")
      dose_use<-input$amount2
      withProgress(message= 'Progress',value=0,{
        #print(isolate(input$Drug2))
        print(dose_use)
        patientN = 50  # captured distributiopatientNum
        groupSet <- list(size = patientN, level = "individual")
        p <- get(input$Drug2)
        
        t1 <- 0
        nd1 = 100
        t2 <- as.numeric(input$ii2)*(nd1-1)+t1
        t.dose <- seq(t1,t2,by=as.numeric(input$ii2))
        interval <- as.numeric(input$ii2)
        missedD <- as.numeric(input$adh2)
        seqTIME <- c(seq(0, missedD, interval), seq(720, 744, interval))
        adm1 <- list(time =  seqTIME, amount = as.numeric(input$amount2), type = 1)
        
        incProgress(0.2,detail="Simulating")
        r <- simulx( model     = 'model.txt',
                     treatment = adm1,
                     group = list(size = patientN),
                     parameter = p,
                     output    = simOutput2,
                     settings =list(seed = 12345))
        
        incProgress(0.6,detail="Done Simulating")
        res1 <- (r)#,z)
        outA <- res1
        outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
        outC <- outB %>% 
          select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
        outD <- gather(outC, "Lesion", "Conc", 2:11)
        outE <- outD
        outE$LESTYPE <- 'Plasma'
        outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
        outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
        outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
        outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
        outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
        outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
        outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
        outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
        outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
        
        incProgress(0.7,detail="Summarizing")
        res2<- outE  %>%
          group_by(time, LESTYPE) %>%
          summarise(lo = quantile(Conc, probs = 0.025, na.rm = T),
                    up = quantile(Conc, probs = 0.975, na.rm = T),
                    med = quantile(Conc, probs = 0.5, na.rm = T))
        
      })
      return(res2)
    }
    return(1)
  })

#Simulations for lesion plot-------- 
   rv <- reactiveValues(trigger = FALSE)
   
   assign("drug_choice", "RIF", envir = .GlobalEnv)
   assign("drug_choice1", "RIF", envir = .GlobalEnv)
   assign("drug_choice2", "RIF", envir = .GlobalEnv)
   assign("drug_choice3", "RIF", envir = .GlobalEnv)
   assign("drug_choice4", "INH", envir = .GlobalEnv)
   assign("drug_choice5", "PZA", envir = .GlobalEnv)
   assign("drug_choice6", "None", envir = .GlobalEnv)
   dose_info<-read.csv("dose.csv")

      output$drug_dose_input <- renderUI({
      selectInput("amount2", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug2], selected = input$Drug2[1])
   })
   output$drug_dose_input2 <- renderUI({
     selectInput("amount_Adh", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug1], selected = input$Drug1[1])
   })
   output$drug_dose_input1 <- renderUI({
     selectInput("amount1", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug], selected = input$Drug[1])
   })
   output$drug_dose_inputM1 <- renderUI({
     selectInput("Multi_amount1", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug], selected = input$Multi_Drug1[1])
   })
   output$drug_dose_inputM2 <- renderUI({
     selectInput("Multi_amount2", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug], selected = input$Multi_Drug2[1])
   })
    output$drug_dose_inputM3 <- renderUI({
      selectInput("Multi_amount3", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug], selected = input$Multi_Drug3[1])
   })
    output$drug_dose_inputM4 <- renderUI({
      selectInput("Multi_amount4", "Amount (mg)", dose_info$Dose[dose_info$Drug == input$Drug], selected = input$Multi_Drug4[1])
   })
   
   
   
   res <- reactive({
    if(drug_choice!=input$Drug){
      print("diff")
      updateNumericInput(session,"amount1", "Amount (mg)", value =  dose_info$Dose[dose_info$Drug == input$Drug][1])
      updateNumericInput(session,"mic1", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Drug][1])
      dose_use<-input$amount1
      assign("drug_choice", input$Drug, envir = .GlobalEnv)
    }else{
      print("same")
      dose_use<-input$amount1
      
    
    print(input$Drug)
    print(dose_use)
    #updateNumericInput(session,"amount1", "Amount (mg)", value =  dose_info$Dose[dose_info$Drug == input$Drug][1])
    withProgress(message= 'Progress',value=0,{
    patientN = 100  # captured distribution
    g <- list(size = patientN, level = "individual")
    p <- get(input$Drug)
    
    
    #updateSelectInput(session, "amount1", choices = dose_info$Dose[dose_info$Drug == input$Drug])
    t1 <- 0
    nd1 = 100
    t2 <- input$ii1*(nd1-1)+t1
    t.dose <- seq(t1,t2,by=input$ii1)
    adm1 <- data.frame(id = rep(1:patientN,each = nd1), 
                        amount=as.numeric(input$amount1), 
                        time=rep(t.dose,patientN), 
                        type = 1)
    
    adhrate <- (input$adh1)/100
    print("Simulating (less than 1 minute)")
    
    incProgress(0.2,detail="Simulating  (less than 1 minute)")
    r <- simulx( model     = 'model.txt',
                 treatment = adm1,
                 group = list(size = patientN),
                 parameter = p,
                 output    = simOutput2,
                 settings =list(seed = 12345))
    
    incProgress(0.6,detail="Done Simulating")
    outA <- r
    outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
    outC <- outB %>% 
      select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
    outD <- gather(outC, "Lesion", "Conc", 2:11)
    outE <- outD
    outE$LESTYPE <- 'Plasma'
    outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
    outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
    outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
    outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
    outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
    outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
    outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
    outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
    outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
    #print(outE)
    
    incProgress(0.7,detail="Summarizing")
    distribution<- outE  %>%
      group_by(time, LESTYPE) %>%
      summarise(lo = quantile(Conc, probs = 0.025, na.rm = T),
                up = quantile(Conc, probs = 0.975, na.rm = T),
                med = quantile(Conc, probs = 0.5, na.rm = T))
    
    #print(distribution)
    })
    return(distribution)
    }
    return(1)
  })
  
  #Adherence simulation-------
  
  res2 <- reactive({
    if(drug_choice!=input$Drug1){
      print("diff")
      updateNumericInput(session,"amount_Adh", "Amount (mg)", value =  dose_info$Dose[dose_info$Drug == input$Drug1][1])
      updateNumericInput(session,"mic_Adh", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Drug1][1])
      dose_use<-input$amount_Adh
      assign("drug_choice", input$Drug1, envir = .GlobalEnv)
    }else{
      print("same")
      dose_use<-input$amount_Adh
      
      
      print(input$Drug)
      print(dose_use)
      #updateNumericInput(session,"amount1", "Amount (mg)", value =  dose_info$Dose[dose_info$Drug == input$Drug][1])
      withProgress(message= 'Progress',value=0,{
        N <- 1
        p <- get(input$Drug1)
        
        
        #updateSelectInput(session, "amount1", choices = dose_info$Dose[dose_info$Drug == input$Drug])
        t1 <- 0
        nd1 = 100
        t2 <- input$ii_Adh*(nd1-1)+t1
        t.dose <- seq(t1,t2,by=input$ii_Adh)
        adm1 <- data.frame(id = rep(1:N,each = nd1), 
                           amount=as.numeric(input$amount_Adh), 
                           time=rep(t.dose,N), 
                           type = 1)
        
        adhrate <- (input$adh1)/100
        adm2 <- adm1[runif(N*nd1)<adhrate,]
        print("Simulating (less than 1 minute)")
        
        incProgress(0.2,detail="Simulating (less than 1 minute)")
        r <- simulx( model     = 'model.txt',
                     treatment = adm2,
                     parameter = p,
                     output    = simOutput1,
                     settings =list(seed = 12345))
        
        incProgress(0.6,detail="Done Simulating")
        outA <- r
        outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
        outC <- outB %>% 
          select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
        outD <- gather(outC, "Lesion", "Conc", 2:11)
        outE <- outD
        outE$LESTYPE <- 'Plasma'
        outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
        outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
        outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
        outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
        outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
        outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
        outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
        outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
        outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
        #print(outE)
        
        incProgress(0.7,detail="Summarizing")
      })
      return(outE)
    }
    return(1)
  })

 
  ##Multi Drug simulation--------
###Drug1-----------
   resMulti1 <- reactive({
     if(drug_choice3!=input$Multi_Drug1){
       print("diff")
       updateSelectInput(session, "Multi_amount1", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug1],
                         selected = dose_info$Dose[dose_info$Drug == input$Multi_Drug1][1])
       updateNumericInput(session,"Multi_mic1", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Multi_Drug1][1])
       dose_use<-as.numeric(input$Multi_amount1)
       assign("drug_choice3", input$Multi_Drug1, envir = .GlobalEnv)
     }else{
       print("same")
       dose_use<-input$Multi_amount1

     #  print(input$Multi_Drug1)
    #   print(dose_use)
       #updateNumericInput(session,"amount1", "Amount (mg)", value =  dose_info$Dose[dose_info$Drug == input$Drug][1])
       withProgress(message= 'Progress',value=0,{
         N = 100  # captured distribution
         g <- list(size = N, level = "individual")
         p <- get(input$Multi_Drug1)
         ii = as.numeric(input$Multi_ii1)
         
         #updateSelectInput(session, "Multi_amount1", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug1])
         t1 <- 0
         nd1 = 100
         t2 <- ii*(nd1-1)+t1
         t.dose <- seq(t1,t2,by=ii)
         adm1 <- data.frame(id = rep(1:N,each = nd1), 
                            amount=as.numeric(input$Multi_amount1), 
                            time=rep(t.dose,N), 
                            type = 1)
         
         print("Simulating")
         
         incProgress(0.2,detail="Simulating - Drug 1  (less than 1 minute)")
         r <- simulx( model     = 'model.txt',
                      treatment = adm1,
                      group = list(size = N),
                      parameter = p,
                      output    = simOutput2,
                      settings =list(seed = 12345))
         
         incProgress(0.6,detail="Done Simulating")
         outA <- r
         outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
         outC <- outB %>% 
           select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
         outD <- gather(outC, "Lesion", "Conc", 2:11)
         outE <- outD
         outE$LESTYPE <- 'Plasma'
         outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
         outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
         outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
         outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
         outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
         outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
         outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
         outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
         outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
         
         
         incProgress(0.7,detail="Summarizing - Drug 1")
         res2<- outE  %>%
           group_by(time, LESTYPE) %>%
           summarise(lo = quantile(Conc, probs = 0.025, na.rm = T),
                     med = quantile(Conc, probs = 0.5, na.rm = T))
         
         
         
         })
       return(res2)
     }
     return(1)
   })
   ###Drug2-----------
   resMulti2 <- reactive({
     if(drug_choice4!=input$Multi_Drug2){
       print("diff")
       updateSelectInput(session,"Multi_amount2", "Amount (mg)", choices =  dose_info$Dose[dose_info$Drug == input$Multi_Drug2])
       updateNumericInput(session,"Multi_mic2", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Multi_Drug2][1])
       dose_use<-input$Multi_amount2
       assign("drug_choice4", input$Multi_Drug2, envir = .GlobalEnv)
     }else{
       print("same")
       dose_use<-as.numeric(input$Multi_amount2)
       
       withProgress(message= 'Progress',value=0,{
         N = 100  # captured distribution
         g <- list(size = N, level = "individual")
         p <- get(input$Multi_Drug2)
         ii = as.numeric(input$Multi_ii2)
         
         #updateSelectInput(session, "Multi_amount2", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug2])
         t1 <- 0
         nd1 = 100
         t2 <- ii*(nd1-1)+t1
         t.dose <- seq(t1,t2,by=ii)
         adm1 <- data.frame(id = rep(1:N,each = nd1), 
                            #amount=600,
                            amount=as.numeric(dose_use), 
                            time=rep(t.dose,N), 
                            type = 1)
         
         print("Simulating")
         
         incProgress(0.2,detail="Simulating - Drug 2  (less than 1 minute)")
         r <- simulx( model     = 'model.txt',
                      treatment = adm1,
                      group = list(size = N),
                      parameter = p,
                      output    = simOutput2,
                      settings =list(seed = 12345))
         
         incProgress(0.6,detail="Done Simulating")
         outA <- r
         outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
         outC <- outB %>% 
           select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
         outD <- gather(outC, "Lesion", "Conc", 2:11)
         outE <- outD
         outE$LESTYPE <- 'Plasma'
         outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
         outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
         outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
         outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
         outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
         outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
         outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
         outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
         outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
         
         incProgress(0.7,detail="Summarizing - Drug 3")
         res2<- outE  %>%
           group_by(time, LESTYPE) %>%
           summarise(lo = quantile(Conc, probs = 0.025, na.rm = T),
                     med = quantile(Conc, probs = 0.5, na.rm = T))
         
         
         
       })
       return(res2)
     }
     return(1)
   })
   ###Drug3-----------
   resMulti3 <- reactive({
     if(drug_choice5!=input$Multi_Drug3){
       print("diff")
       updateSelectInput(session,"Multi_amount3", "Amount (mg)", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug3])
       updateNumericInput(session,"Multi_mic3", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Multi_Drug3][1])
       dose_use<-input$Multi_amount3
       assign("drug_choice5", input$Multi_Drug3, envir = .GlobalEnv)
     }else{
       print("same")
       dose_use<-as.numeric(input$Multi_amount3)
       
       withProgress(message= 'Progress',value=0,{
         N = 100  # captured distribution
         g <- list(size = N, level = "individual")
         p <- get(input$Multi_Drug3)
         ii = as.numeric(input$Multi_ii3)
         
         #updateSelectInput(session, "Multi_amount3", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug3])
         t1 <- 0
         nd1 = 100
         t2 <- ii*(nd1-1)+t1
         t.dose <- seq(t1,t2,by=ii)
         adm1 <- data.frame(id = rep(1:N,each = nd1), 
                            amount=as.numeric(dose_use), 
                            time=rep(t.dose,N), 
                            type = 1)
         
         print("Simulating")
         
         incProgress(0.2,detail="Simulating - Drug 3  (less than 1 minute)")
         r <- simulx( model     = 'model.txt',
                      treatment = adm1,
                      group = list(size = N),
                      parameter = p,
                      output    = simOutput2,
                      settings =list(seed = 12345))
         
         incProgress(0.6,detail="Done Simulating")
         outA <- r
         outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
         outC <- outB %>% 
           select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
         outD <- gather(outC, "Lesion", "Conc", 2:11)
         outE <- outD
         outE$LESTYPE <- 'Plasma'
         outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
         outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
         outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
         outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
         outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
         outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
         outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
         outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
         outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
         
         incProgress(0.7,detail="Summarizing - Drug 3")
         res2<- outE  %>%
           group_by(time, LESTYPE) %>%
           summarise(lo = quantile(Conc, probs = 0.025, na.rm = T),
                     med = quantile(Conc, probs = 0.5, na.rm = T))
         
         
         
       })
       return(res2)
     }
     return(1)
   })
 
   
   ###Drug4-----------
   resMulti4 <- reactive({
     if(drug_choice6!=input$Multi_Drug4){
       print("diff")
       updateSelectInput(session,"Multi_amount4", "Amount (mg)", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug4])
       updateNumericInput(session,"Multi_mic4", "MIC (mg/L)", value =  dose_info$MIC[dose_info$Drug == input$Multi_Drug4][1])
       dose_use<-input$Multi_amount4
       assign("drug_choice6", input$Multi_Drug4, envir = .GlobalEnv)
     }else{
       print("same")
       dose_use<-as.numeric(input$Multi_amount4)
       
       
       #  print(input$Multi_Drug1)
       #   print(dose_use)
       #updateNumericInput(session,"amount1", "Amount (mg)", value =  dose_info$Dose[dose_info$Drug == input$Drug][1])
       withProgress(message= 'Progress',value=0,{
         N = 100  # captured distribution
         g <- list(size = N, level = "individual")
         p <- get(input$Multi_Drug4)
         ii = as.numeric(input$Multi_ii4)
         
        # updateSelectInput(session, "Multi_amount4", choices = dose_info$Dose[dose_info$Drug == input$Multi_Drug4])
         t1 <- 0
         nd1 = 100
         t2 <- ii*(nd1-1)+t1
         t.dose <- seq(t1,t2,by=ii)
         adm1 <- data.frame(id = rep(1:N,each = nd1), 
                            #amount=600,
                            amount=as.numeric(dose_use), 
                            time=rep(t.dose,N), 
                            type = 1)
         
         print("Simulating")
         
         incProgress(0.2,detail="Simulating - Drug 4  (less than 1 minute)")
         r <- simulx( model     = 'model.txt',
                      treatment = adm1,
                      group = list(size = N),
                      parameter = p,
                      output    = simOutput2,
                      settings =list(seed = 12345))
         
         incProgress(0.6,detail="Done Simulating")
         outA <- r
         outB <- bind_cols(outA$Cc, outA$L1, outA$L2, outA$L3, outA$L4, outA$L5, outA$L6, outA$L7, outA$L8, outA$L9)
         outC <- outB %>% 
           select(time, Cc, L1, L2, L3, L4, L5, L6, L7, L8, L9)
         outD <- gather(outC, "Lesion", "Conc", 2:11)
         outE <- outD
         outE$LESTYPE <- 'Plasma'
         outE[outE$Lesion == "L1", "LESTYPE"] <- 'Lung'
         outE[outE$Lesion == "L2", "LESTYPE"] <- 'Necrotic nodule'
         outE[outE$Lesion == "L3", "LESTYPE"] <- 'Closed nodule caseum'
         outE[outE$Lesion == "L4", "LESTYPE"] <- 'Caseous fibrotic nodule'
         outE[outE$Lesion == "L5", "LESTYPE"] <- 'Caseum from cavity'
         outE[outE$Lesion == "L6", "LESTYPE"] <- 'Cavity wall'
         outE[outE$Lesion == "L7", "LESTYPE"] <- 'Fibrotic tissue'
         outE[outE$Lesion == "L8", "LESTYPE"] <- 'Small nodule'
         outE[outE$Lesion == "L9", "LESTYPE"] <- 'Fungal ball'
         
         incProgress(0.7,detail="Summarizing - Drug 4")
         res2<- outE  %>%
           group_by(time, LESTYPE) %>%
           summarise(lo = quantile(Conc, probs = 0.025, na.rm = T),
                     med = quantile(Conc, probs = 0.5, na.rm = T))
         
         
         
       })
       return(res2)
     }
     return(1)
   })   
   
     

 #Output boxes for lesions--------       
    output$aucBox <- renderInfoBox({
      res <- res()
      outA <- res %>% 
        filter(LESTYPE == input$lesion)
      
      outB <- LogAUC(outA$time, outA$med)
      
      infoBox(
        "Mean daily AUC", paste0(prettyNum((outB["AUC"]), format = 'g', digits = 3), " mg.hr/L"),# icon = icon("list"),'expCas$cmax'
        color = "light-blue", fill = F
      )
    })
    
    output$cmaxBox <- renderInfoBox({
      res <- res()
      outA <- res %>% 
        group_by(LESTYPE) %>% 
        summarise(cmax = max(med)) %>% 
        filter(LESTYPE == input$lesion)
        
      
      infoBox(
        "Cmax", paste0(prettyNum(outA$cmax, format = 'g', digits = 3), " mg/L"),# icon = icon("list"),'expCas$cmax'
        color = "light-blue"
      )
    })
    
    output$tmicBox <- renderInfoBox({
      res = res()
      outA <- res
      mic <- input$mic1
      outE <- outA %>% 
        mutate(tabove = ifelse(med < mic, 1, 0)) %>% 
        group_by(LESTYPE) %>%
        summarise(totalhours = (sum(tabove)-1)) %>% 
        mutate(totalhours = ifelse(totalhours ==-1, 0, totalhours))
      outF <- filter(outE, LESTYPE == input$lesion)
      infoBox(
        "Time below MIC", paste0(prettyNum(((outF$totalhours)),format = 'g', digits = '3'), ' h/d'),# icon = icon("thumbs-up", lib = "glyphicon"),
        color = "light-blue"
      )
    })
    
    
    
    
    
    file_set<-c('RIF', 'INH', 'PZA', 'MFX', 'CFZ','KAN', 'LZD')
    vars_to_read<-c('ka_pop','Cl_pop','V_pop','Q2_pop','V2_pop','tg_pop',"rpl1_pop","rpl2_pop","rpl3_pop","rpl4_pop","rpl5_pop",
                    "rpl6_pop","rpl7_pop","rpl8_pop","rpl9_pop","kpl1","kpl2","kpl3","kpl4","kpl5",
                    "kpl6","kpl7","kpl8","kpl9")
    literal_read<-c('ka','Cl','V','Q2','V2','tg',"rpl1","rpl2","rpl3","rpl4","rpl5",
                    "rpl6","rpl7","rpl8","rpl9","kpl1","kpl2","kpl3","kpl4","kpl5",
                    "kpl6","kpl7","kpl8","kpl9")
    df_tbl3 <- as.data.frame(setNames(replicate(length(literal_read),numeric(0), simplify = F), literal_read[1:length(literal_read)]))
    for(fi_s in file_set){
      df_rds<-readRDS(paste(fi_s,'.rds',sep=""))
      df_rds<-data.frame(as.list(df_rds))
      df_rds<-df_rds[,colnames(df_rds)%in%vars_to_read]
      df_tbl3<-rbind(df_tbl3,df_rds)
    }
    colnames(df_tbl3)<-literal_read
    rownames(df_tbl3)<-file_set
    df_tbl3<-t(df_tbl3)
    df_rds<-data.frame(
      Parameter=literal_read
    )
    df_tbl3<-cbind(df_rds,df_tbl3)
    output$tbl1 <- renderTable({ df_tbl3 })
    
    output$myImage <- renderImage({
      list(src = "about.png",
           contentType = 'image/png',
           #width = 400,
           height = 500,
           alt = "Box Model of pk equations")
    }, deleteFile = FALSE)

    #Output lesion plot ---- 

output$lesion_plot <- renderPlot({
  withProgress(message= 'Progress',value=0.9, detail = "Plotting - almost there", {  
  res = res()

    mic = input$mic1
    limits = input$yaxis
    
   res$LESTYPE <- factor(res$LESTYPE, c('Plasma', 'Lung', 'Cavity wall','Small nodule','Caseum from cavity','Closed nodule caseum','Caseous fibrotic nodule','Necrotic nodule', 'Fibrotic tissue', 'Fungal ball'))

resCFZ <- filter(res, LESTYPE != 'Fungal ball', LESTYPE != 'Closed nodule caseum')   
resLZD <- filter(res, LESTYPE != 'Fungal ball')  

if(input$Drug == 'LZD'){
  resA <- resLZD }
    else
  {if(input$Drug == 'CFZ'){
    resA <- resCFZ}
    else
    {resA <- res}
}

   
   p <- ggplot(resA, aes(time-720, med)) +
     geom_ribbon(aes(ymin = lo, ymax = up), alpha = 0.2, fill = "#21a6d5", size = 0.01) +
     geom_line(color = 'black', size = 1) +
     xlab("Time after dose at steady state (hrs)") +
     scale_x_continuous(breaks = seq(0, 744, by=12)) +
     scale_y_continuous(limits = c(0, NA)) +
     ylab("Concentration (mg/L)") +
     geom_hline(yintercept = mic, linetype = 2) +
     facet_wrap(~LESTYPE, scales = limits) +
     theme_bw(base_family = "Helvetica") +
     theme(strip.background = element_rect(fill = 'white', colour = 'white'),
           panel.grid.major = element_blank(), panel.grid.minor = element_blank())
   if (input$ilog==TRUE)
           p=p + scale_y_log10()
  })
   print(p)
  
 }, height = 500)
 
 #Adh plot--------
 
    output$Adh_plot <- renderPlot({
      withProgress(message= 'Progress',value=0.9, detail = "Plotting - almost there", {
      res = res2()

      mic = input$mic_Adh
      limits = input$yaxis
      
      res$LESTYPE <- factor(res$LESTYPE, c('Plasma', 'Lung', 'Cavity wall','Small nodule','Caseum from cavity','Closed nodule caseum','Caseous fibrotic nodule','Necrotic nodule', 'Fibrotic tissue', 'Fungal ball'))

      resCFZ <- filter(res, LESTYPE != 'Fungal ball', LESTYPE != 'Closed nodule caseum')   
      resLZD <- filter(res, LESTYPE != 'Fungal ball')  
      
      
      if(input$Drug == 'CFZ'){
        resA <- resCFZ }
      else
      {if(input$Drug == 'LZD'){
        resA <- resLZD}
        else
        {resA <- res}
      }
      
      x_limits = c(input$day1*24, (input$day1*24)+24)
      
      adhPlot <- ggplot(resA, aes(time, Conc)) +
        geom_line(color = 'black', size = 1) +
        xlab("Time after dose (hrs)") +
        scale_x_continuous(limits = x_limits, breaks = seq(0, 744, by=12)) +
        scale_y_continuous(limits = c(0, NA)) +
        ylab("Concentration (mg/L)") +
        geom_hline(yintercept = mic, linetype = 2) +
        facet_wrap(~LESTYPE, scales = limits) +
        theme_bw(base_family = "Helvetica") +
        theme(strip.background = element_rect(fill = 'white', colour = 'white'),
              panel.grid.major = element_blank(), panel.grid.minor = element_blank())
      if (input$ilog==TRUE)
        adhPlot=adhPlot + scale_y_log10()
      })
      print(adhPlot)
      
    }, height = 500)    
    
    
    #Day select plot-------
 output$timePlot <- renderPlot({
   res = res2()
   
   resLesion <- filter(res, LESTYPE == input$lesion)
   timePlot <- ggplot(resLesion, aes(time, Conc)) +
     geom_line(color = 'black', size = 1) +
     scale_x_continuous(limits = c(0, 744)) +
     scale_y_continuous(limits = c(0, NA)) +
     theme_void()
   
   print(timePlot)
 })

    #Lesion PK plot-----   
    output$LesionPK <- renderPlot({
      res1 = resMulti1()
      res2 = resMulti2()
      res3 = resMulti3()
      res4 = resMulti4()
      
      drug1 = input$Multi_Drug1
      drug2 = input$Multi_Drug2
      drug3 = input$Multi_Drug3
      drug4 = input$Multi_Drug4
      
      selectedDrug <- input$Multi_Drug5

      mic1 = input$Multi_mic1
      mic2 = input$Multi_mic2
      mic3 = input$Multi_mic3
      mic4 = input$Multi_mic4
       
      resM1 <- mutate(res1, Drug = "Drug 1", drugName = drug1, mic = mic1)
      resM2 <- mutate(res2, Drug = "Drug 2", drugName = drug2, mic = mic2)
      resM3 <- mutate(res3, Drug = "Drug 3", drugName = drug3, mic = mic3)
      resM4 <- mutate(res4, Drug = "Drug 4", drugName = drug4, mic = mic4)

      resM5 <- bind_rows(resM1, resM2, resM3, resM4)
       
      pkData <- filter(resM5, Drug == selectedDrug)
      
      #legendCheck <- input$legend
      
      legendPosition <- ifelse(input$legend==T, "right", "none")
      
      PlotPK <- ggplot(pkData, aes(x = (time-720), y = med, color = LESTYPE)) +
        geom_line() +
        scale_x_continuous(limits = c(0, 24), breaks = seq(0, 24, by = 12)) +
        xlab("Time after dose (hrs)") +
        scale_color_brewer(palette = "Paired")+
        ggtitle(label = pkData$drugName) +
        ylab("Conc mg/L") +
        geom_line(aes((x = time-720), y = pkData$mic), color = 'black', linetype = 2) +
        theme_bw(base_family = "Helvetica") +
        theme(panel.grid.major = element_blank(), 
              panel.grid.minor = element_blank(), 
              legend.position = legendPosition,
              plot.title = element_text(hjust = 0.5))
      
      if (input$ilog==TRUE)
        PlotPK=PlotPK + scale_y_log10()
      
      print(PlotPK)
    }, height = 220, width = 300)    
    
#Output Multi Drug -----
    output$multiFacet1 <- renderPlot({
      withProgress(message= 'Progress',value=0.9, detail = "Plotting - almost there", {
      res1 = resMulti1()
      res2 = resMulti2()
      res3 = resMulti3()
      res4 = resMulti4()
      
      mic1 = as.numeric(input$Multi_mic1)
      drug1 = input$Multi_Drug1
      
      mic2 = as.numeric(input$Multi_mic2)
      drug2 = input$Multi_Drug2
      
      mic3 = as.numeric(input$Multi_mic3)
      drug3 = input$Multi_Drug3
      
      mic4 = as.numeric(input$Multi_mic4)
      drug4 = input$Multi_Drug4
      
      timebar1 <-  res1 %>% 
        mutate(tabove = ifelse(med > mic1, 1, 0), DRUG = paste("Drug 1 - ", drug1, sep = "")) %>% 
        select(LESTYPE, DRUG, time, tabove)
      
      timebar2 <-  res2 %>% 
        mutate(tabove = ifelse(med > mic2, 1, 0), DRUG = paste("Drug 2 - ", drug2, sep = "")) %>% 
        select(LESTYPE, DRUG, time, tabove)
      
      timebar3 <-  res3 %>% 
        mutate(tabove = ifelse(med > mic3, 1, 0), DRUG = paste("Drug 3 - ", drug3, sep = "")) %>% 
        select(LESTYPE, DRUG, time, tabove)
      
      timebar4 <-  res4 %>% 
        mutate(tabove = ifelse(med > mic4, 1, 0), DRUG = paste("Drug 4 - ", drug4, sep = "")) %>% 
        select(LESTYPE, DRUG, time, tabove)
      
     mergeLego <- bind_rows(timebar1, timebar2, timebar3, timebar4)
      filter_d <- mergeLego %>% 
        filter(tabove == 1) #%>% 
        # filter(DRUG %in% c("RIF","INH","PZA"))
      
      histoDF = filter_d %>%
        group_by(LESTYPE) %>% 
        arrange(time) %>% # sort using longitudinal time
        mutate(time_rounded = (time+1) - ( (time+1) %% 1 ) ) %>% # This attributes a bin to each observation. Here 1hr is the size of the bin.
        mutate(nDrugs=ave(time_rounded, time_rounded, FUN=seq_along)) # This calculates the position on the Y axis: 1, 2, 3, 4...
      
      none_data1 <- data_frame(time_rounded = rep(seq(0, 25, 1)+720,3), nDrugs = c(rep(1, 26), rep(2, 26), rep(3, 26)), DRUG = "none")
      none_data2 <- data_frame(time_rounded = rep(seq(0, 25, 1)+720,4), nDrugs = c(rep(1, 26), rep(2, 26), rep(3, 26), rep(4, 26)), DRUG = "none")
      
      if(input$Multi_Drug4=="None"){
        emptyBlocks <- none_data1
        drugTime = 75
        seqBreaks = seq(1, 3, 1)
      }else{
        emptyBlocks <- none_data2
        drugTime = 100
        seqBreaks = seq(1, 4, 1)
      }
      
      histoDF$LESTYPE <- factor(histoDF$LESTYPE, c('Plasma', 'Lung', 'Cavity wall','Small nodule','Caseum from cavity','Closed nodule caseum','Caseous fibrotic nodule','Necrotic nodule', 'Fibrotic tissue', 'Fungal ball'))
      histoDF$DRUG <- factor(histoDF$DRUG, c(paste("Drug 1 - ", drug1, sep = ""), paste("Drug 2 - ", drug2, sep = ""), paste("Drug 3 - ", drug3, sep = ""), paste("Drug 4 - ", drug4, sep = ""))) 
      
      percDrugHours <- histoDF %>% 
        group_by(LESTYPE) %>% 
        summarise(perc = paste(prettyNum(length(nDrugs)/drugTime*100, format = f, digits = 1), "%", sep = ""))
      
      
      # Make the plot (middle)
      legoPlot <- ggplot(histoDF, aes(x=time_rounded-720.5, y=nDrugs)) +
        geom_point(data = emptyBlocks, shape = 22, size = 4.5, aes(x=time_rounded-720.5, y=nDrugs))+
        geom_point(shape = 22, size = 4.5, aes(color = DRUG, fill = DRUG))+
        scale_x_continuous(limits = c(0, 24), breaks = seq(0, 24, by = 1), labels = c(0,  "",  "",  "",  "",  "",  "6",  "",  "",  "", "", "", 12, "", "", "", "", "", 18, "", "", "", "", "", 24), minor_breaks = c(0, 24, 1)) +
        scale_y_continuous(breaks = seqBreaks, limits = c(0, 5))+
        geom_text(data = percDrugHours, x = 12, y = 5, label = percDrugHours$perc)+
        #facet_wrap(~LESTYPE)+
        xlab("Time after dose (hrs)") +
        ylab("Number of drugs above MIC") +
        theme(legend.position = "none") +
        scale_fill_manual(values = porterfield) +
        scale_color_manual(values = porterfield) +
        theme_tufte(base_family = "Helvetica") +
        #theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend position = "none")) +
        theme(panel.grid.major = element_blank(), legend.position = "top") +
        facet_wrap(~LESTYPE, scales = "free", ncol = 3)
      
      
      })
      print(legoPlot)
    }, height = 500, width = 950) 

    
output$multiFacet2 <- renderPlot({
  
  res1 = resMulti1()
  res2 = resMulti2()
  res3 = resMulti3()
  res4 = resMulti4()
  
  mic1 = as.numeric(input$Multi_mic1)
  drug1 = input$Multi_Drug1
  
  mic2 = as.numeric(input$Multi_mic2)
  drug2 = input$Multi_Drug2
  
  mic3 = as.numeric(input$Multi_mic3)
  drug3 = input$Multi_Drug3
  
  mic4 = as.numeric(input$Multi_mic4)
  drug4 = input$Multi_Drug4
  
  timebar1 <-  res1 %>% 
    mutate(tabove = ifelse(lo > mic1, 1, 0), DRUG = paste("Drug 1 - ", drug1, sep = "")) %>% 
    select(LESTYPE, DRUG, time, tabove)
  
  timebar2 <-  res2 %>% 
    mutate(tabove = ifelse(lo > mic2, 1, 0), DRUG = paste("Drug 2 - ", drug2, sep = "")) %>% 
    select(LESTYPE, DRUG, time, tabove)
  
  timebar3 <-  res3 %>% 
    mutate(tabove = ifelse(lo > mic3, 1, 0), DRUG = paste("Drug 3 - ", drug3, sep = "")) %>% 
    select(LESTYPE, DRUG, time, tabove)
  
  timebar4 <-  res4 %>% 
    mutate(tabove = ifelse(lo > mic4, 1, 0), DRUG = paste("Drug 4 - ", drug4, sep = "")) %>% 
    select(LESTYPE, DRUG, time, tabove)
  
  mergeLego <- bind_rows(timebar1, timebar2, timebar3, timebar4)
  filter_d <- mergeLego %>% 
    filter(tabove == 1) #%>% 
  # filter(DRUG %in% c("RIF","INH","PZA"))
  
  histoDF = filter_d %>%
    group_by(LESTYPE) %>% 
    arrange(time) %>% # sort using longitudinal time
    mutate(time_rounded = (time+1) - ( (time+1) %% 1 ) ) %>% # This attributes a bin to each observation. Here 1hr is the size of the bin.
    mutate(nDrugs=ave(time_rounded, time_rounded, FUN=seq_along)) # This calculates the position on the Y axis: 1, 2, 3, 4...
  
  none_data1 <- data_frame(time_rounded = rep(seq(0, 25, 1)+720,3), nDrugs = c(rep(1, 26), rep(2, 26), rep(3, 26)), DRUG = "none")
  none_data2 <- data_frame(time_rounded = rep(seq(0, 25, 1)+720,4), nDrugs = c(rep(1, 26), rep(2, 26), rep(3, 26), rep(4, 26)), DRUG = "none")
  
  if(input$Multi_Drug4=="None"){
    emptyBlocks <- none_data1
    drugTime = 75
    seqBreaks = seq(1, 3, 1)
  }else{
    emptyBlocks <- none_data2
    drugTime = 100
    seqBreaks = seq(1, 4, 1)
  }
  
  histoDF$LESTYPE <- factor(histoDF$LESTYPE, c('Plasma', 'Lung', 'Cavity wall','Small nodule','Caseum from cavity','Closed nodule caseum','Caseous fibrotic nodule','Necrotic nodule', 'Fibrotic tissue', 'Fungal ball'))
  histoDF$DRUG <- factor(histoDF$DRUG, c(paste("Drug 1 - ", drug1, sep = ""), paste("Drug 2 - ", drug2, sep = ""), paste("Drug 3 - ", drug3, sep = ""), paste("Drug 4 - ", drug4, sep = ""))) 
  
  percDrugHours <- histoDF %>% 
    group_by(LESTYPE) %>% 
    summarise(perc = paste(prettyNum(length(nDrugs)/drugTime*100, format = f, digits = 1), "%", sep = ""))
  
  
  # Make the plot (middle)
  legoPlot <- ggplot(histoDF, aes(x=time_rounded-720.5, y=nDrugs)) +
    geom_point(data = emptyBlocks, shape = 22, size = 4.5, aes(x=time_rounded-720.5, y=nDrugs))+
    geom_point(shape = 22, size = 4.5, aes(color = DRUG, fill = DRUG))+
    scale_x_continuous(limits = c(0, 24), breaks = seq(0, 24, by = 1), labels = c(0,  "",  "",  "",  "",  "",  "6",  "",  "",  "", "", "", 12, "", "", "", "", "", 18, "", "", "", "", "", 24), minor_breaks = c(0, 24, 1)) +
    scale_y_continuous(breaks = seqBreaks, limits = c(0, 5))+
    geom_text(data = percDrugHours, x = 12, y = 5, label = percDrugHours$perc)+
    #facet_wrap(~LESTYPE)+
    xlab("Time after dose (hrs)") +
    ylab("Number of drugs above MIC") +
    theme(legend.position = "none") +
    scale_fill_manual(values = porterfield) +
    scale_color_manual(values = porterfield) +
    theme_tufte(base_family = "Helvetica") +
    #theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend position = "none")) +
    theme(panel.grid.major = element_blank(), legend.position = "top") +
    facet_wrap(~LESTYPE, scales = "free", ncol = 3)
  
  
  
  print(legoPlot)
}, height = 500, width = 950) 

 #Output cavity plot-----
 output$plot3 <- renderPlot({
   withProgress(message= 'Progress',value=0.9, detail = "Plotting - almost there", {
   res = res1()

 outF <- res %>% 
   filter(LESTYPE == 'Caseum from cavity')

  mic = input$mic2
 if(('Typical exposure'%in%input$percentile) & ('Low exposure'%in%input$percentile)){
   plotCavity <- ggplot(outF, aes(time-720, med)) +
     #geom_ribbon(aes(ymin = lo, ymax = up), alpha = 0.2, fill = "#21a6d5", size = 0.01) +
     geom_line(color = 'black', size = 1) +
     geom_line(data = outF, aes(x = time-720, y = lo), color = 'red', size = 1) +
     xlab("Time after dose at steady state (hrs)") +
     scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
     scale_y_continuous(limits = c(0, NA)) +
     ylab("Concentration (mg/L)") +
     geom_hline(yintercept = mic, linetype = 2) +
     theme_bw(base_family = "Helvetica") +
     theme(strip.background = element_rect(fill = 'white', colour = 'white'),
           panel.grid.major = element_blank(), panel.grid.minor = element_blank())
 }
 if(!('Typical exposure'%in%input$percentile) & ('Low exposure'%in%input$percentile)){
   plotCavity <- ggplot(outF, aes(time-720, med)) +
     #geom_ribbon(aes(ymin = lo, ymax = up), alpha = 0.2, fill = "#21a6d5", size = 0.01) +
     geom_line(data = outF, aes(x = time-720, y = lo), color = 'red', size = 1) +
     xlab("Time after dose at steady state (hrs)") +
     scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
     scale_y_continuous(limits = c(0, NA)) +
     ylab("Concentration (mg/L)") +
     geom_hline(yintercept = mic, linetype = 2) +
     theme_bw(base_family = "Helvetica") +
     theme(strip.background = element_rect(fill = 'white', colour = 'white'),
           panel.grid.major = element_blank(), panel.grid.minor = element_blank())
 }
 if(('Typical exposure'%in%input$percentile) & !('Low exposure'%in%input$percentile)){
   plotCavity <- ggplot(outF, aes(time-720, med)) +
     #geom_ribbon(aes(ymin = lo, ymax = up), alpha = 0.2, fill = "#21a6d5", size = 0.01) +
     geom_line(color = 'black', size = 1) +
     xlab("Time after dose at steady state (hrs)") +
     scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
     scale_y_continuous(limits = c(0, NA)) +
     ylab("Concentration (mg/L)") +
     geom_hline(yintercept = mic, linetype = 2) +
     theme_bw(base_family = "Helvetica") +
     theme(strip.background = element_rect(fill = 'white', colour = 'white'),
           panel.grid.major = element_blank(), panel.grid.minor = element_blank())
 }
 if(!('Typical exposure'%in%input$percentile) & !('Low exposure'%in%input$percentile)){
   plotCavity <- ggplot(outF, aes(time-720, med)) +
     #geom_ribbon(aes(ymin = lo, ymax = up), alpha = 0.2, fill = "#21a6d5", size = 0.01) +
     xlab("Time after dose at steady state (hrs)") +
     scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
     scale_y_continuous(limits = c(0, NA)) +
     ylab("Concentration (mg/L)") +
     geom_hline(yintercept = mic, linetype = 2) +
     theme_bw(base_family = "Helvetica") +
     theme(strip.background = element_rect(fill = 'white', colour = 'white'),
           panel.grid.major = element_blank(), panel.grid.minor = element_blank())
 }

 
 if (input$ilog==TRUE)
   plotCavity=plotCavity + scale_y_log10()
   })
 print(plotCavity)
 }, height = 250)
 
#Output lung plot------ 

 output$plot2 <- renderPlot({
   res = res1()
   
   outF <- filter(res, LESTYPE == "Lung")
   mic = input$mic2
   
   if(('Typical exposure'%in%input$percentile) & ('Low exposure'%in%input$percentile)){
    plotLung <- ggplot(outF, aes(time-720, med)) +
      geom_line(color = 'black', size = 1) +
      geom_line(data = outF, aes(x = time-720, y = lo), color = 'red', size = 1) +
      xlab("Time after dose at steady state (hrs)") +
      scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
      scale_y_continuous(limits = c(0, NA)) +
      ylab("Concentration (mg/L)") +
      geom_hline(yintercept = mic, linetype = 2) +
      theme_bw(base_family = "Helvetica") +
      theme(strip.background = element_rect(fill = 'white', colour = 'white'),
             panel.grid.major = element_blank(), panel.grid.minor = element_blank())
       plotLung=plotLung + geom_line(color = 'black', size = 1)
       plotLung=plotLung + geom_line(data = outF, aes(x = time-720, y = lo), color = 'red', size = 1)
   }
    if(('Typical exposure'%in%input$percentile) & !('Low exposure'%in%input$percentile)){
         plotLung <- ggplot(outF, aes(time-720, med)) +
           geom_line(color = 'black', size = 1) +
           xlab("Time after dose at steady state (hrs)") +
           scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
           scale_y_continuous(limits = c(0, NA)) +
           ylab("Concentration (mg/L)") +
           geom_hline(yintercept = mic, linetype = 2) +
           theme_bw(base_family = "Helvetica") +
           theme(strip.background = element_rect(fill = 'white', colour = 'white'),
                 panel.grid.major = element_blank(), panel.grid.minor = element_blank())
         plotLung=plotLung + geom_line(color = 'black', size = 1)
    }
         if(!('Typical exposure'%in%input$percentile) & ('Low exposure'%in%input$percentile)){
           plotLung <- ggplot(outF, aes(time-720, med)) +
             geom_line(data = outF, aes(x = time-720, y = lo), color = 'red', size = 1) +
             xlab("Time after dose at steady state (hrs)") +
             scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
             scale_y_continuous(limits = c(0, NA)) +
             ylab("Concentration (mg/L)") +
             geom_hline(yintercept = mic, linetype = 2) +
             theme_bw(base_family = "Helvetica") +
             theme(strip.background = element_rect(fill = 'white', colour = 'white'),
                   panel.grid.major = element_blank(), panel.grid.minor = element_blank())
           plotLung=plotLung + geom_line(data = outF, aes(x = time-720, y = lo), color = 'red', size = 1)
      }
       if(!('Typical exposure'%in%input$percentile) & !('Low exposure'%in%input$percentile)){
         plotLung <- ggplot(outF, aes(time-720, med)) +
           xlab("Time after dose at steady state (hrs)") +
           scale_x_continuous(limits = c(0, 24), breaks = c(0, 12, 24)) +
           scale_y_continuous(limits = c(0, NA)) +
           ylab("Concentration (mg/L)") +
           geom_hline(yintercept = mic, linetype = 2) +
           theme_bw(base_family = "Helvetica") +
           theme(strip.background = element_rect(fill = 'white', colour = 'white'),
                 panel.grid.major = element_blank(), panel.grid.minor = element_blank())
      }
    if (input$ilog==TRUE)
       plotLung=plotLung + scale_y_log10()
     
   print(plotLung)
 }, height = 250)

 
 output$lung <- renderUI({
   res = res1()
   outA <- filter(res, LESTYPE == 'Lung')
   mic = input$mic2
   outB <- outA %>% 
     group_by(LESTYPE) %>% 
     mutate(tabove = ifelse(med < mic, 1, 0)) %>% 
     summarise(auc = sum(med), cmax = max(med), totalhours = (sum(tabove)-1))%>% 
     mutate(totalhours = ifelse(totalhours ==-1, 0, totalhours))
   auc <- paste0("AUC = ", prettyNum(outB$auc, format = 'g', digits = 3), " mg.hr/L")
   cmax <- paste0("Cmax = ", prettyNum(outB$cmax, format = 'g', digits = 3), " mg/L")
   tmic <- paste0("Time below MIC = ", prettyNum(outB$totalhours, format = 'g', digits = 3), " hrs")
   HTML(paste(auc, cmax, tmic, sep="<br/>"))
   
 })
 
 output$cavity <- renderUI({
   res = res1()
   outA <- filter(res, LESTYPE == 'Caseum from cavity')
   mic = input$mic2
   outB <- outA %>% 
     group_by(LESTYPE) %>% 
     mutate(tabove = ifelse(med < mic, 1, 0)) %>% 
     summarise(auc = sum(med), cmax = max(med), totalhours = (sum(tabove)-1))%>% 
     mutate(totalhours = ifelse(totalhours ==-1, 0, totalhours))
   auc <- paste0("AUC = ", prettyNum(outB$auc, format = 'g', digits = 3), " mg.hr/L")
   cmax <- paste0("Cmax = ", prettyNum(outB$cmax, format = 'g', digits = 3), " mg/L")
   tmic <- paste0("Time below MIC = ", prettyNum(outB$totalhours, format = 'g', digits = 3), " hrs")
   HTML(paste(auc, cmax, tmic, sep="<br/>"))
 })
 
 #Output Cavity tables----------
 output$table2 <- renderTable({
   res = res1()
   outA <- filter(res, LESTYPE == 'Lung')
   mic = input$mic2
   
   aucMed <- LogAUC(outA$time, outA$med)
   aucMedb <- aucMed[1]
   aucLo <- LogAUC(outA$time, outA$lo)
   aucLob <- aucLo[1]
   outB <- outA %>% 
     group_by(LESTYPE) %>% 
     mutate(tabove = ifelse(med < mic, 1, 0)) %>% 
     summarise(Cmax = max(med), totalhours = (sum(tabove)-1))%>% 
     mutate("Time below MIC" = ifelse(totalhours == -1, 0, totalhours), Patient = "Typical exposure", AUC = aucMedb) %>% 
     select(Patient, AUC, Cmax, "Time below MIC")
   
   outC <- outA %>% 
     group_by(LESTYPE) %>% 
     mutate(tabove = ifelse(lo < mic, 1, 0)) %>% 
     summarise(Cmax = max(lo), totalhours = (sum(tabove)-1))%>% 
     mutate("Time below MIC" = ifelse(totalhours == -1, 0, totalhours), Patient = "Low exposure", AUC = aucLob) %>% 
     select(Patient, AUC, Cmax, "Time below MIC")
   
   outD <- bind_rows(outC, outB)
   outD
 })
 
 output$table3 <- renderTable({
   res = res1()
   outA <- filter(res, LESTYPE == 'Caseum from cavity')
   mic = input$mic2
   
   aucMed <- LogAUC(outA$time, outA$med)
   aucMedb <- aucMed[1]
   aucLo <- LogAUC(outA$time, outA$lo)
   aucLob <- aucLo[1]
   
   outB <- outA %>% 
     group_by(LESTYPE) %>% 
     mutate(tabove = ifelse(med < mic, 1, 0)) %>% 
     summarise(Cmax = max(med), totalhours = (sum(tabove)-1)) %>% 
     mutate("Time below MIC" = ifelse(totalhours == -1, 0, totalhours), Patient = "Typical exp", AUC = aucMedb) %>% 
     select(Patient, AUC, Cmax, "Time below MIC")
   
   outC <- outA %>% 
     group_by(LESTYPE) %>% 
     mutate(tabove = ifelse(lo < mic, 1, 0)) %>% 
     summarise(Cmax = max(lo), totalhours = (sum(tabove)-1))%>% 
     mutate("Time below MIC" = ifelse(totalhours == -1, 0, totalhours), Patient = "Low exp", AUC = aucLob) %>% 
     select(Patient, AUC, Cmax, "Time below MIC")
   
   outD <- bind_rows(outC, outB)
   outD
 })
 
}