Personal Details

Age Group

Gender

Cyclosporine Medication

Dose Recommendation

Cyclosporine Medication

Concurrent Disorders

route of administration

absorption

delay

distribution

elimination

output

pkmodelCode.R

ui.R

Download

library(shinydashboard)


sidebar <- dashboardSidebar(width = 300,
                            hr(),
                            sidebarMenu(id="tabs",
                                        menuItem("Plot", tabName = "plot", icon = icon("line-chart"), selected=TRUE)
                                        
                                        
                                          ),
                            hr(),
                            conditionalPanel("input.tabs=='plot'",
                                             sidebarMenu(
                                               menuItem("Personal Details", tabName = "details", icon = icon("chevron-circle-right"),selected=TRUE ),
                                               
                                               menuItem("Disease State", tabName = "DisState", icon = icon("chevron-circle-right")),
                                               menuItem("Cyclosporine PK Details", tabName = "PkDetails", icon = icon("chevron-circle-right")),
                                               
                                               
                                               menuItem("Administration", tabName = "admin", icon = icon("chevron-circle-right") ,selected=TRUE),
                                               menuItem("Parameterization", icon = icon("chevron-circle-right"),
                                                        fluidRow(
                                                          column(1),
                                                          column(10,
                                                                 radioButtons("parameterization","",c("rate constant" = "1","clearance" = "2"),selected = "2")
                                                          )) ),
                                               menuItem("Model", icon = icon("chevron-circle-right"),
                                                        menuSubItem("Absorption", tabName = "absorption", icon = icon("angle-right")),
                                                        menuSubItem("Distribution", tabName = "distribution", icon = icon("angle-right")),
                                                        menuSubItem("Elimination", tabName = "elimination", icon = icon("angle-right"))
                                               ),
                                               
                                              
                                               
                                               
                                               
                                               menuItem("Output", tabName = "output", icon = icon("chevron-circle-right"))
                                               
                                             )
                                             
                            )
                            
                            
)

body <- dashboardBody(
  tabItems(
    tabItem(tabName = "plot",
            fluidRow( 
              box(width = 12, status = "primary",
                  downloadButton('downloadPlot','Download'),  br(),
                  plotOutput("plot",  height="300px")
              ),
              tabItems(
                
                tabItem(tabName = "details",
                        box(width = 4, status = "primary",solidHeader = TRUE, title="Personal Details",
                            sliderInput("age", "Age(yrs):", value=30, min=1, max = 100, step=1),
                            sliderInput("weight", "Weight(Kgs):", value=75, min=1, max = 125, step=1),
                            sliderInput("height", "height(inches,12 inches = 1 feet):", value=66, min=36, max = 80, step=1)
                            
                            
                        ),
                        box(width = 4, status = "primary", solidHeader = TRUE, title = "Age Group",        
                            radioButtons("ageG", "Select the Age Group",
                                         c("Pediatric (2 yrs - 16 yrs)" = "pediatric","Adult (16 yrs -60 yrs)"="adult","Geriatric (60 yrs-80 yrs)"="geriatric"),selected="adult")
                        ),
                        box(width = 4, status = "primary", solidHeader = TRUE, title="Gender",      
                            radioButtons("gender", "Select the Gender Type",
                                         c("Male" = "male","Female"="female"),selected="male")
                            
                        )
                        
                        
                ),
                tabItem(tabName = "PkDetails",
                        box(width = 4, status = "primary", solidHeader = TRUE,title="Cyclosporine Medication",
                            sliderInput("css", "Average Concentration(ng/mL)", value=250, min=100, max = 2000, step=1),
                                         
                            sliderInput("F", "Bioavailability:", value=0.3, min=0.3, max = 0.3, step=0.1)
                        ),
                        
                        #conditionalPanel(condition = "input.administration == 'infusion'",
                                         #box(width = 4, status = "warning", solidHeader = TRUE,title="Therapeutic Range",
                                           #  htmlOutput("printCssAvgI")
                                             
                                        # )
                       # ),
                        #conditionalPanel(condition = "input.administration == 'oral'",
                                        # box(width = 4, status = "warning", solidHeader = TRUE,title="Therapeutic Range",
                                           #  htmlOutput("printCssAvgO")
                                             
                                       #  )
                       # ),
                        box(width = 4, status = "primary", solidHeader = TRUE,title="Dose Recommendation",
                            htmlOutput("printDosage"),
                            htmlOutput("DoseRange")
                            
                        )
                        
                        
                        
                        
                        
                        
                ),
                
                tabItem(tabName = "DisState",
                        box(width = 4, status = "primary", solidHeader = TRUE,title="Cyclosporine Medication",
                            radioButtons("disease", "",
                                         c("Renal Transplant" = "RenalTransplant","Liver Transplant"="LiverTransplant","Heart Transplant"="HeartTransplant","BoneMarrow Transplant"="BoneMarrowTransplant","Stem Cell Transplant"="StemCellTransplant","Rheumatoid Arthritis" = "RhematoidArthritis","Psoriasis" = "Psoriasis","Atopic Dermatitis"="AtopicDermatitis","Endogenous Uveitis"="EndogenousUveitis"),selected="RenalTransplant")
                        ),
                        
                        
                        box(width = 4, status = "primary", solidHeader = TRUE,title="Concurrent Disorders",
                            radioButtons("condisease", "",
                                         c("Normal Liver" = "NormalLiver","Liver Disorder" = "LiverDisorder"),selected="NormalLiver")
                        )
                ),
                tabItem(tabName = "admin",
                        box(width = 4, status = "primary", solidHeader = TRUE, title="route of administration",          
                            radioButtons("administration", "",
                                         c("iv infusion" = "infusion","oral" = "oral"),selected="oral")
                        ),
                        box(width = 4, status = "primary",          
                            sliderInput("tfd", "Time of first dose:", value=0, min=0, max = 20, step=1),
                            sliderInput("nd", "Number of doses:", value=6, min=0, max = 10, step=1)
                        ),
                        box(width = 4, status = "primary",          
                            sliderInput("ii", "Interdose interval:", value = 12, min = 10, max = 15, step=1),
                            
                            conditionalPanel(condition = "input.administration == 'infusion'",
                                             sliderInput("tinf", "Infusion time:", value = 1, min = 0, max = 5, step=0.2)
                            )
                        )
                ),
                tabItem(tabName = "absorption",
                        conditionalPanel(condition = "input.administration == 'oral'",
                                         box(width = 4, status = "primary", solidHeader = TRUE, title="absorption",       
                                             radioButtons("absorption","",c("first order" = "1"))
                                         ),
                                         box(width = 4, status = "primary", solidHeader = TRUE, title="delay",          
                                             
                                             conditionalPanel(condition = "input.absorption == '1'",
                                                              radioButtons("delay1","",c("none" = "0","lag time" = "1"))
                                             )
                                         ),
                                         box(width = 4, status = "primary",       
                                             conditionalPanel(condition = "input.absorption == '1'",
                                                              sliderInput("ka", "rate constant ka:", value = 0.5, min = 0, max = 3, step=0.1)
                                             ),
                                             conditionalPanel(condition = "(input.absorption == '1' & input.delay1 == '1') ",
                                                              sliderInput("tlag", "lag time Tlag:", value = 1, min = 0, max = 10, step=0.5)
                                             )
                                         )
                        )
                ),
                tabItem(tabName = "distribution",
                        #                         fluidRow( 
                        box(width = 4, status = "primary", solidHeader = TRUE, title="distribution",   
                            #                             h5("Number of compartments:"),
                            radioButtons("distribution","Number of compartments:",c("1" = "1","2" = "2"), inline=TRUE),
                            sliderInput("v", "volume V:(L/kg)", value = 4, min = 4, max = 5, step=0.1)
                        ),
                        conditionalPanel(condition = "input.distribution != '1' & input.parameterization=='1'",
                                         box(width = 4,   status = "primary",         
                                             sliderInput("k12", "transition rate constant k12:", value = 0.4, min = 0, max = 2, step=0.05),
                                             sliderInput("k21", "transition rate constant k21:", value = 0.2, min = 0, max = 2, step=0.05)
                                         )
                        ),
                        conditionalPanel(condition = "input.distribution != '1' & input.parameterization=='2'",
                                         box(width = 4,   status = "primary",         
                                             sliderInput("v2", "periph. comp. volume V2:", value = 20, min = 2, max = 40, step=2),
                                             sliderInput("q2", "inter comp. clearance Q2:", value = 4, min = 1, max = 10, step=0.5)
                                         )
                        )
                        
                ),
                tabItem(tabName = "elimination",
                        box(width = 4, status = "primary", solidHeader = TRUE, title="elimination",          
                            radioButtons("elimination","",c("linear" = "1"))
                        ),
                        box(width = 4, status = "primary",          
                            conditionalPanel(condition = "input.elimination=='1' & input.parameterization=='1'",
                                             sliderInput("k", "elimination rate constant k:", value = 0.1, min = 0, max = 2, step=0.05)
                            ),
                            conditionalPanel(condition = "input.elimination == '1' & input.parameterization=='2'",
                                             sliderInput("Cl", "Clearance Cl:", value = 4, min = 4, max = 5, step=1)
                            )
                        )
                ),
                tabItem(tabName = "output",
                        box(width = 4, status = "primary", solidHeader = TRUE, title="output",          
                            radioButtons("log", "", c("linear scale" = FALSE,"log scale" = TRUE))  
                        ),
                        box(width = 4, status = "primary",
                            sliderInput("range", "time range", min = -10, max = 200, value = c(-5,100), step=5),
                            sliderInput("ngp", "grid size", min = 50, max = 1000, value = 500, step=50)
                        ),
                        box(width = 4, status = "primary",
                            sliderInput("lsize", "line width", min = 0, max = 5, value = 0.75, step=0.25)
                        )
                )#ad
                
                
                
                
                
                
              )#before plot
            )
    ),
    
    tabItem(tabName = "pkmodel",
            box( width = NULL, status = "primary", solidHeader = TRUE, title="pkmodelCode.R",                
                 downloadButton('downloadData1', 'Download'),
                 br(),br(),
                 verbatimTextOutput("RFile")
            )
    ),
    tabItem(tabName = "ui",
            box( width = NULL, status = "primary", solidHeader = TRUE, title="ui.R",
                 downloadButton('downloadData2', 'Download'),
                 br(),br(),
                 pre(includeText("ui.R"))
            )
    ),
    tabItem(tabName = "server",
            box( width = NULL, status = "primary", solidHeader = TRUE, title="server.R",
                 downloadButton('downloadData3', 'Download'),
                 br(),br(),
                 pre(includeText("server.R"))
            )
    )
    
  )
)

dashboardPage(
  dashboardHeader(title = "Cyclosprorine Drug"),
  sidebar,
  body
)

server.R

Download

# This is the server logic for a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#

library(shinydashboard)
library(mlxR) 
library(ggplot2)

shinyServer(function(input, output) {
  
  l.text <- ("library(mlxR)\n")
  
  iModel <- "
  [LONGITUDINAL]
  input = {V, Cl}
  EQUATION:
  Cc = pkmodel(V, Cl)
  "
  
  oModel <- 
    "
  [LONGITUDINAL]
  input = {ka, V, Cl}
  EQUATION:
  Cc = pkmodel(ka, V, Cl)
  "
  myModel <- inlineModel(oModel,"pk_model.txt")
  
  
  pkmodel.text <- ("
                   res <- pkmodel(t,adm,p)
                   
                   print(ggplot(data=res, aes(x=time, y=cc)) + geom_line(size=1) +
                   xlab('time (h)') + ylab('concentration (ng/L)'))
                   ")
CalABW<-reactive({
  
    IBWm=50+(2.3)*((input$height)-60)
    cIBWm=(0.3)*(IBWm)
  
    IBWw=45.5+(2.3)*((input$height)-60)
    cIBWw=(0.3)*(IBWw)
  
  ABWm=0
  
  ABWw=0
  
  if(input$height>60 & input$gender=="male")
  {
    print("value of ibw and cib")
    print(input$weight)
    print(IBWm)
    print(cIBWm)
    print(cIBWm+IBWm)
    
    if(input$weight<(cIBWm+IBWm))
    {
      print("inside if")
      ABWm=input$weight
      
      
    }else
    {
      print("inside else")
      ABWm=54.7+0.4*((input$weight)-(54.7))
    }
    print(ABWm)
    print("above adjusted body weight")
    return(ABWm)
  }
  
  if(input$height>60 & input$gender=="female")
  {
    
    
    if(input$weight<(cIBWw+IBWw))
    {
      ABWw=input$weight
      
      
    }else
    {
      ABWw=54.7+0.4*((input$weight)-(54.7))
      
    }
    
    return(ABWw)
  }
  
  
  
  
})
  
  
  

  
  CalTRDose <- reactive({
    param.name=NULL
    param.value=NULL
    
    print("Value of ideal body weight")
    print(CalABW())
    
    RT1D=(CalABW())*6*(0.5)
    RT2D=(CalABW())*12*(0.5)
    RT=list(RT1D,RT2D)
    
    
    LT1D=(CalABW())*4*(0.5)
    
    LT2D=(CalABW())*12*(0.5)
    LT=list(LT1D,LT2D)
    
    HT1D=(CalABW())*4*(0.5)
    HT2D=(CalABW())*10*(0.5)
    
    HT=list(HT1D,HT2D)
    
    
    BMT1D=(CalABW())*2*(0.5)
    BMT2D=(CalABW())*15*(0.5)
    
    BMT=list(BMT1D,BMT2D)
    
    SCT1D=(CalABW())*2*(0.5)
    
    
    SCT2D=(CalABW())*15*(0.5)
    
    SCT=list(SCT1D,SCT2D)
    
    
    R1D=(CalABW())*3*(0.5)
    
    R2D=(CalABW())*5*(0.5)
    
    R=list(R1D,R2D)
    
    
    P1D=(CalABW())*2.5*(0.5)
    P2D=(CalABW())*5*(0.5)
    
    P=list(P1D,P2D)
    
    AD1D=(CalABW())*2.5*(0.5)
    AD2D=(CalABW())*5*(0.5)
    
    AD=list(AD1D,AD2D)
    
    E1D=(CalABW())*5*(0.5)
    E2D=(CalABW())*7*(0.5)
    
    
    E=list(E1D,E2D)
    edf<-expand.grid(weight=input$weight,disease=c("RenalTransplant","LiverTransplant","HeartTransplant","BoneMarrowTransplant","StemCellTransplant","RhematoidArthritis","Psoriasis","AtopicDermatitis","EndogenousUveitis"))
    
    
    
    edf$rt<-ifelse((input$disease=="RenalTransplant"),(list(RT)),0)
    
    edf$lt<-ifelse((input$disease=="LiverTransplant"),(list(LT)),0)
    edf$ht<-ifelse((input$disease=="HeartTransplant"),(list(HT)),0)
    edf$bmt<-ifelse((input$disease=="BoneMarrowTransplant"),(list(BMT)),0)
    edf$sct<-ifelse((input$disease=="StemCellTransplant"),(list(SCT)),0)
    edf$r<-ifelse((input$disease=="RhematoidArthritis"),(list(R)),0)
    edf$p<-ifelse((input$disease=="Psoriasis"),(list(P)),0)
    edf$ad<-ifelse((input$disease=="AtopicDermatitis"),(list(AD)),0)
    edf$e<-ifelse((input$disease=="EndogenousUveitis"),(list(E)),0)
   
    
    adf<-subset(edf,disease==input$disease )
    
    
    ad<-adf[, sapply(adf, function(x) is.list(x))]
    TRdoses<-unlist(ad)
    
    
    
    param.name=c(param.name,'DoseMin')
    param.value=c(param.value,TRdoses[1])
    
    param.name=c(param.name,'DoseMax')
    param.value=c(param.value,TRdoses[2])
    
    dosedf<-data.frame(name=param.name,value=param.value)
    
    
    return(dosedf)
  })
  
  caldose<-reactive({
    param.name=NULL
    param.value=NULL
    
    Clm=0
    Clf=0
    #Formula for Clearance Calculation
    if(input$gender=='male')
    {
      
      
      Clm=(CalABW())*(60/1000)
      
    
  
      
    }
    else
    {
      Clf=(CalABW())*(60/1000)
    }
    
    #concurrent disease 
    #for Normal Liver in dAdult and Geriatric
    NClm=6*(Clm)          #60/1000
    
    print("d: value of clearance after L/Hour")
    print(NClm)
    
    NClw=6*(Clf)
  
    
    #Liver disorder  Clearance for Adults and Gediatric
    DLClm=3*(Clm)
    DLClw=3*(Clf)
    

    
    #check when pediatric add some more if required
    
    #get the values for dosage regimen calculation 
    d<-input$css
    t=input$ii
    
    # Part II calculation , multiply dosing interval with Css and divide by 1000
    c=(((input$ii)*(d))/((1000)))
    
    print("d: value of the c ")
    print(c)
    
    
    #----------------------Calculate thalf,cl,vd,Cmax,Cmin,ke,dose Adult Male
    
    NACl<-NClm
    DNclAm<-((NACl)*(c))
    
    
    print("d: value of NaCl")
    print(DNclAm)
    #----------------------Calculation for Adult female Normal Liver----
    NAFCl<-NClw
    DNclFm<-((NAFCl)*(c))
    
    
    #----------------------Calculation for Adult male Disorder Liver----
    DLAClm<-DLClm
    DLclAm<-((DLAClm)*(c))
    
    #----------------------Calculation for Adult female Disorder Liver----
    DLAClw<-DLClw
    DNclAw<-((DLAClw)*(c))
    
    #----------------------Calculate thalf,cl,vd,Cmax,Cmin,ke,dose Geriatric Male
    
    NGCl<-NClm
    DNclGm<-((NACl)*(c))
    
    #----------------------Calculation for Geriatric  female Normal Liver----
    NAGFCl<-	NClw
    DNclG<-	((NAFCl)*(c))
    
    
    #----------------------Calculation for Geriatric male Disorder Liver----
    DLGClm<-DLAClm
    DLGlAm<-DLclAm
    
    
    #----------------------Calculation for Geriatric female Disorder Liver----
    DLGClw<-DLAClw
    DNclAw<-DNclAw
    
    
    #Pediatric Clearance 
    NClPw=10*(Clf)
    NClPm=10*(Clm)
    
    DLClm=3*(Clm)
    DLClw=3*(Clf)
    
    #----------------------Calculation for Pediatric female Disorder Liver----
    DLPClw<-DLClw
    DNclPw<-DNclAw
    
    
    #----------------------Calculation for Pediatric male Disorder Liver----
    
    DLClPm<-DLClm
    DLDclPm<-DLClPm
    
    
    #----------------------Calculation for Pediatric female Normal Liver----
    
    NPwCl<-NClPw
    DNclPw<-((NPwCl)*(c))
    
    #----------------------Calculate thalf,cl,vd,Cmax,Cmin,ke,dose Pediatric Normal liver
    
    NPmCl<-NClPm
    DNPmclAm<-((NPmCl)*(c))
    
    #debug is giving correct answer till this
    
    MNA=c(NACl,DNclAm)
    FNA=c(NAFCl,DNclFm)
    MLDA=c(DLAClm,DLclAm)
    FLDA=c(DLAClw,DNclAw)
    MNG=c(NGCl,DNclGm)
    FNG=c(NAGFCl,DNclG)
    MDLG=c(DLGClm,DLGlAm)
    FDLG=c(DLGClw,DNclAw)
    MNP=c(NPmCl,DNPmclAm)
    FNP=c(NPwCl,DNclPw)
    MDLP=c(DLClPm,DLDclPm)
    NDLP=c(DLPClw,DNclPw)
    
    edf<-expand.grid(age=input$age,height=input$height,weight=input$weight,ageG=c("pediatric","adult","geriatric"),gender=c("male","female"),administration=c("infusion","oral"),condisease=c("NormalLiver","LiverDisorder"),disease=c("RenalTransplant","LiverTransplant","HeartTransplant","BoneMarrowTransplant","StemCellTransplant","RhematoidArthritis","Psoriasis","AtopicDermatitis","EndogenousUveitis"),css=input$css)
    
    edf$DNClAm<-ifelse(((input$gender=="male") & (input$condisease=="NormalLiver")& (input$ageG =="adult")&(NACl>0)), ( list(MNA)),0)
    edf$DNClAw<-ifelse(((input$gender=="female") & (input$condisease=="NormalLiver")& (input$ageG =="adult")& (NAFCl>0)),(list(FNA)),0)
    
    edf$DDLClAm<-ifelse(((input$gender=="male") & (input$condisease=="LiverDisorder")& (input$ageG =="adult")&(DLAClm>0)),(list(MLDA)),0)
    
    edf$DDLClAw<-ifelse(((input$gender=="female") & (input$condisease=="LiverDisorder")& (input$ageG =="adult")&(DLAClw>0)),(list(FLDA)),0)
    
    
    edf$DNClGm<-ifelse(((input$gender=="male") & (input$condisease=="NormalLiver")& (input$ageG =="geriatric")&(NGCl>0)),(list(MNG)),0)
    
    edf$DNClGw<-ifelse(((input$gender=="female") & (input$condisease=="NormalLiver")& (input$ageG =="geriatric")&(NAGFCl>0)),(list(FNG)),0)
    
    edf$DDLClGm<-ifelse(((input$gender=="male") & (input$condisease=="LiverDisorder")& (input$ageG =="geriatric")&(DLGClm>0)),(list(MDLG)),0)
    
    edf$DDLClGw<-ifelse(((input$gender=="female") & (input$condisease=="LiverDisorder")& (input$ageG =="geriatric")&(DLGClw>0)),(list(FDLG)),0)
    
    
    edf$DNClPm<-ifelse(((input$gender=="male") & (input$condisease=="NormalLiver") &(input$ageG =="pediatric")&(NPmCl>0)),(list(MNP)),0)
    edf$DNClPw<-ifelse(((input$gender=="female") & (input$condisease=="NormalLiver") &(input$ageG =="pediatric")&(NPwCl>0)),(list(FNP)),0)
    
    edf$DDLClPm<-ifelse(((input$gender=="male") & (input$condisease=="LiverDisorder") &(input$ageG =="pediatric")&(DLClPm>0)),(list(MDLP)),0)
    edf$DDLClPw<-ifelse(((input$gender=="female") & (input$condisease=="LiverDisorder") &(input$ageG =="pediatric")&(DLPClw>0)),(list(NDLP)),0)
    
    
    
    adf<-subset(edf,ageG==input$ageG & gender==input$gender & administration==input$administration & condisease==input$condisease & disease==input$disease )
    
    ad<-adf[, sapply(adf, function(x) is.list(x))]
    ClDose<-unlist(ad)
    print("d: cldose result")
    print(ClDose)
    
    
    
    CD<-ClDose[2]
    #Formula for Clearance Calculation
    if(input$administration=='oral')
    {
      CD=(ClDose[2])/(0.3)
      print("value of CD")
      print(CD)
    }
    else
    {
      CD=ClDose[2]
    }
    print("d: value of calculated dose")
    print(CD)
    #calculate Avg Css for Disease Therapeutic range  Dose1 and Dose2
    
    
    CssAvg1o=((0.3*1000)*(CalTRDose()[[2]][1]))/((ClDose[1])*(input$ii))
    CssAvg1i=((CalTRDose()[[2]][1])*(1000))/((ClDose[1])*(input$ii))
    
    CssAvg2o=((0.3*1000)*(CalTRDose()[[2]][2]))/((ClDose[1])*(input$ii))
    CssAvg2i=((CalTRDose()[[2]][2])*(1000))/((ClDose[1])*(input$ii))
    
    param.name=c(param.name,'Cl')
    param.value=c(param.value,ClDose[1])
    
    param.name=c(param.name,'mdose')
    param.value=c(param.value,CD)
    
    
    param.name=c(param.name,'CssAvgMino')
    param.value=c(param.value,CssAvg1o)
    
    param.name=c(param.name,'CssAvgMini')
    param.value=c(param.value,CssAvg1i)
    
    param.name=c(param.name,'CssAvgMaxo')
    param.value=c(param.value,CssAvg2o)
    
    param.name=c(param.name,'CssAvgMaxi')
    param.value=c(param.value,CssAvg2i)
    
    param.name=c(param.name,'DoseMin')
    param.value=c(param.value,CalTRDose()[[2]][1])
    
    param.name=c(param.name,'DoseMax')
    param.value=c(param.value,CalTRDose()[[2]][2])
    
    pkvalues<-data.frame(name=param.name,value=param.value)
    
    
    
    return(pkvalues)
  })
  
  
  
  output$printCssAvgO<-reactive({
    print("value of Average concentration")
    a<-caldose()[[2]][5]
    b<-caldose()[[2]][3]
    
    paste0("<b>","Maximum Css ",as.integer(a)," micrograms" ,"<br>", "Minimum Css " ,as.integer(b)," micrograms","</b>")
    
    
   
    
    
  })
  
  output$printCssAvgI<-reactive({
    print("value of Average concentration")
    a<-caldose()[[2]][5]
    b<-caldose()[[2]][3]
    
    paste0("<b>","Maximum Css " ,as.integer(a)," micrograms" ,"</b>","<br>", "Minimum Css " ,"<b>",as.integer(b)," micrograms","</b>")
    
    
    
    
    
  })
  
  output$printDosage<-reactive({
    a<-caldose()[[2]][2]
    paste0("<b>","Dosage Recommended For every ",input$ii,"  Hrs  is ", as.integer(a)," milligrams","</b>")
  })
  
  #output$DoseRange<-reactive({
   # a<-CalTRDose()[[2]][1]
   # b<-CalTRDose()[[2]][2]
   # paste0("<b>","Maximum Recommended Dosage " ,as.integer(a)," mg" ,"</b>","<br>", "Minimum Recommended Dosage " ,"<b>",as.integer(b)," mg","for",input$disease,"</b>")
    
    
 # })
  output$DoseRange<-reactive({
    a<-CalTRDose()[[2]][1]
    b<-CalTRDose()[[2]][2]
    paste0("<b>",input$disease,"(",as.integer(a)," mg","-",as.integer(b),"mg", ")","</b>")
  })
  
  
  
  recaldose <- reactive({
    
    Doselst=list(caldose()[[2]][2],caldose()[[2]][7],caldose()[[2]][8])
    
    vod=(input$v) *(input$weight)
    
    pkMaxlist=list()
    pkMinlist=list()
    i=1
    for(Dose in Doselst)
    {
      
      if(input$administration=='oral')
      {
        Dose<-Dose*0.3
        myModel <- inlineModel(oModel,"pk_model.txt")
        p <- c(ka=input$ka, V=vod, Cl=caldose()[[2]][1])
        
        
        
        adm <- list(tfd=input$tfd, ii=input$ii, amount=Dose*input$F)
        
      }
      else
      {
        myModel <- inlineModel(iModel,"pk_model.txt")
        
        p <- c( V=vod, Cl=caldose()[[2]][1])
        
        adm <- list(tfd=input$tfd, ii=input$ii, amount=Dose )
        
        
      }
      
      out<-list(name="Cc",time='steady.state')
      
      
      
      
      #----------------------------------------------------    
      res <- exposure(model=myModel, parameter=p, output=out, treatment=adm)
      
      #---------------------------------------------------
     
     
      
      
      pkMaxlist[[i]]<-res$Cc[["cmax"]]
      pkMinlist[[i]]<-res$Cc[["cmin"]]
      
      rm(p,adm,res)
      
      
      i=i+1
      
      
    }
    
    
    
   
    
    mylst=c(pkMaxlist,pkMinlist)
    
    
    
    
    
    return(mylst)
  })
  
  output$plot <- renderPlot({
    
    pl <- myplot(r()[[1]]$f, input$lsize, input$log)
    
    
    print(pl)
  })
  
  myplot <- function(r,lsize,ilog){
    
    yi=recaldose()
    
    ylst=c(yi[[3]],yi[[5]])
    clst=c("green","Red")
    
    pl=ggplotmlx(data=r, aes(x=time, y=cc )) + geom_line(size=lsize)+
      (geom_hline(yintercept=ylst, linetype="dashed", color = clst  )) +  
      geom_text(aes(x=0.5,y=0.5),label="MTC",hjust=1, size=4) +
      geom_text(aes(x=0.5,y=0.1),label="MEC",hjust=1, size=4) + 
      geom_line(size=lsize) + xlab("time(h)") +ylab("Concentration(ng)")
    if (ilog==TRUE)
      pl=pl + scale_y_log10()
    return(pl)
  }  
  
  r <- reactive({ 
    param.name=NULL
    param.value=NULL
    
    
    if(input$administration=="oral")
    {
      dose=caldose()[[2]][2]*0.3
      
    }
    else{
      dose=caldose()[[2]][2]
    }
    
    
    if (input$administration=="oral"){
      if (input$absorption=="1"){
        if (input$delay1=="1"){
          param.name=c(param.name,'Tlag')
          param.value=c(param.value,input$tlag)
        }
        
        param.name=c(param.name,'ka')
        param.value=c(param.value,input$ka)
        
        
      }
    }
    param.name=c(param.name,'V')
    param.value=c(param.value,((input$v)*(input$weight)))
    
    if (input$distribution!="1"){
      if (input$parameterization=="1"){
        param.name=c(param.name,'k12','k21')
        param.value=c(param.value,input$k12,input$k21)
      }else{
        param.name=c(param.name,'Q2','V2')
        param.value=c(param.value,input$q2,input$v2)
      }
    }
    
    
    if (input$elimination=="1"){
      if (input$parameterization=="1"){
        param.name=c(param.name,'k')
        param.value=c(param.value,input$k)
      }else{
        param.name=c(param.name,'Cl')
        param.value=c(param.value,caldose()[[2]][1])
      }
    }
    p=param.value
    names(p)=param.name
    t.value=seq(input$range[1],input$range[2],length.out=(input$ngp+1))
    t1=input$tfd
    t2=input$ii*(input$nd-1)+t1
    a.names <- c("amount","tfd","nd","ii")
    a.values <- c(dose,input$tfd,input$nd,input$ii)
    if (t2>=t1){
      t.dose=seq(t1,t2,by=input$ii)
      adm <- list(time=t.dose, amount=dose)
    }else{
      adm <- list(time=t1, amount=0)
    }
    if (input$administration == 'infusion'){
      adm$rate <- dose/input$tinf
      a.names <- c(a.names, "tinf")
      a.values <- c(a.values, input$tinf)
    }
    #----------------------------------------------------    
    res   <- pkmodel(time=t.value,treatment=adm,parameter=p)
    #----------------------------------------------------    
    
    a.text <- 'adm <- list('
    if (input$nd==0){
      a.text <- 'adm <- list(amount=0, time=0'
    } else if(input$nd==1){
      a.text <- paste0('adm <- list(amount=',dose,', time=',input$tfd)
    } else{
      t1=input$tfd
      t2=input$ii*(input$nd-1)+t1
      a.text <- paste0('adm <- list(amount=',dose,
                       ', time=seq(',t1,', ',t2,', by=',input$ii,')')
    }
    if (input$administration == 'infusion'){
      a.text <- paste0(a.text,', tinf=',input$tinf,')')
    }else{
      a.text <- paste0(a.text,')')      
    }
    K <- length(param.value)
    p.text <- 'p <- c('
    for (k in (1:(K-1))){
      p.text <- paste0(p.text,param.name[k],'=',param.value[k],', ')
    }
    p.text <- paste0(p.text,param.name[K],'=',param.value[K],')')
    t.text <- paste0('t <- seq(',input$range[1],', ',input$range[2],
                     ', length=',length.out=input$ngp,')')
    pkmodel.text <- paste0(l.text,a.text,'\n',p.text,'\n',t.text,'\n',pkmodel.text)
    
    parameter <- data.frame(row.names= names(p), value=p)
    treatment <- data.frame(row.names= a.names, value=a.values)
    res <- list(parameter=p, f=res, treatment=treatment)
    out <- list(res,pkmodel.text)
    return(out)
  })
  
  
  output$tablef <- renderTable({ r()[[1]]$f })
  
  output$tablep <- renderTable({ r()[[1]]$parameter },include.colnames=FALSE)
  
  output$tablea <- renderTable({ r()[[1]]$treatment },include.colnames=FALSE)
  
  output$RFile  <- renderText(r()[[2]])
  
  output$downloadTablef <- downloadHandler(
    filename = paste("concentration", Sys.Date(), ".csv", sep=""),
    content = function(file) {
      write.csv(r()[[1]]$f, file, row.names=FALSE)
    }
  )
  output$downloadTablep <- downloadHandler(
    filename = paste("parameter", Sys.Date(), ".csv", sep=""),
    content = function(file) {
      write.table(r()[[1]]$parameter, file, col.names=FALSE, sep=",")
    }
  )
  output$downloadTablea <- downloadHandler(
    filename = paste("dosage", Sys.Date(), ".csv", sep=""),
    content = function(file) {
      write.table(r()[[1]]$treatment, file, col.names=FALSE, sep=",")
    }
  )
  
  output$downloadData1 <- downloadHandler(
    filename = "pkmodelCode.R",
    content = function(file) {
      write(r()[[2]], file)
    }
  )
  
  output$downloadData2 <- downloadHandler(
    filename = "ui.R",
    content = function(file) {
      con        = file("ui.R", open = "r")
      lines      = readLines(con)
      close(con)
      write(lines, file)
    }
  )
  
  output$downloadData3 <- downloadHandler(
    filename = "server.R",
    content = function(file) {
      con        = file("server.R", open = "r")
      lines      = readLines(con)
      close(con)
      write(lines, file)
    }
  )
  
  output$downloadPlot <- downloadHandler(
    filename <- function() {
      paste("concentration", Sys.Date(), ".png", sep="") },
    content <- function(file) {
      png(file, width = 980, height = 600, units = "px", pointsize = 12, bg = "white", res = NA)
      #       png(file, bg = "white", res = NA)
      pl <- myplot(r()[[1]]$f, input$lsize, input$log)
      print(pl)
      dev.off()},
    contentType = 'image/png'
  )
  
  
  
  
  
  
  

  
  
  
  
  
  
  
  
  
  
  
  
})