#NOTES
# Main script for running model and outputting results.
# Text to the right of the "#" sign are comments and are not processed. 
# Comments are an essential part of model code and should be used to describe what the code is doing.
# This promotes transparency and helps avoid and identify errors.


###############################################################################
#Start of script###############################################################
###############################################################################

# remove previous contents
rm(list=ls())

# Set the working directory by replacing the text "G:/DSU PLS TSD R model" with your current directory
# NOTE: Use the / rather than \\ symbol 
# NOTE: Put the working directory in "" symbols (to make it a character vector)

setwd("G:/DSU PLS TSD R model")

# load in DES functions in the file DSU_DesFunctions.R 
# NOTE: Must be in the same directory

source("DSU_DesFunctions.R")


################################################################################
# GLOBAL VARIABLES #############################################################
################################################################################



# Global variables - placed in base environment

util.init <- 0.7 # initial utility
drc <- 0.035 # discount rate for costs
drq <- 0.035 # discount rate for QALYs

#npats <- 50000 # number of patients
npats <- 500  # use this if running through line by line

# utility multipliers for hip fractures and vert fractures
umult.hfrac <- 0.75
umult.vfrac <- 0.90

cost.hfrac <- 7000
cost.vfrac <- 3000

cost.int <- 500 # annual cost of intervention

mortprobhip <- 0.05 # probability of dying from a hip fracture

###################################################################################
#set options########################################################################
###################################################################################


# Debug mode flag: this will print out the event list and accrued costs and qalys 
# as the simulation is being run
dbg <- T

# Flag for whether individual level patient details should be stored and output
ind <- T 

if (ind==T){
  PatData <- vector("list", length=npats) # empty list with 50000 elements
}


##################################################################################    
# Run the simulation##############################################################
###################################################################################

# to fix simulation results - use set.seed. Useful for debugging as removes random variation

set.seed(1)                   # or any integer
RunSim()                      # run simulation




##################################################################################
#examine results ##################################################################
###################################################################################

# To get summary stats
tot.costs.int # total (discounted) costs for intervention arm
tot.qalys.int # total (discounted) qalys for intervetnion arm 
tot.costs.noint # total (discounted) costs for no intervention arm
tot.qalys.noint # total (discounted) qalys for no intervention arm
tot.dcosts # Total difference in costs between intervention and no intervention pairs
tot.dqalys # Total difference in qalys between intervention and no intervention pairs


# means
tot.costs.int/npats 
tot.qalys.int/npats  
tot.costs.noint/npats 
tot.qalys.noint/npats 
tot.dcosts/npats
tot.dqalys/npats


# With ind mode: lapply function to count the number of 
# events 

# Number of deaths not relating to hip fractures in intervention arm
sum(sapply(PatData, function(x) x$int$deathother))  

# Number of deaths from hip fractures in intervention arm
sum(sapply(PatData, function(x) x$int$deathhip))

# Total number of hip fractures in intervention arm
sum(sapply(PatData, function(x) x$int$nhip))

# Total number of vert fractures in intervention arm
sum(sapply(PatData, function(x) x$int$nvert))


# For non intervention arm equivalents of above, change 'int' to 'noint'

sum(sapply(PatData, function(x) x$noint$deathother))  
sum(sapply(PatData, function(x) x$noint$deathhip))
sum(sapply(PatData, function(x) x$noint$nhip))
sum(sapply(PatData, function(x) x$noint$nvert))


# To access individual patient information for a single patient
# Say the 37th patient...

PatData[[37]]$noint # No intervention copy of the patient

PatData[[37]]$int # Intervention copy of the same patient

# To access the event list for a particular patient

PatData[[37]]$int$evtlist
PatData[[37]]$noint$evtlist

##################################################################################
#output results to excel###########################################################
###################################################################################

# Create object for exporting to Excel 
ExcelData <- data.frame(
  ptnum=1:npats,
  itthip=rep(NA, npats),
  ittvert1=rep(NA, npats),
  ittvert2=rep(NA, npats),
  ittdeath=rep(NA, npats), 
  ihipcount=rep(NA, npats),
  ivertcount=rep(NA, npats),
  idthhip=rep(NA,npats),
  idthall=rep(NA, npats),
  icosts=rep(NA, npats),
  iqalys=rep(NA, npats),
  ntthip=rep(NA, npats),
  nttvert1=rep(NA, npats),
  nttvert2=rep(NA, npats),
  nttdeath=rep(NA, npats), 
  nhipcount=rep(NA, npats),
  nvertcount=rep(NA, npats),
  ndthhip=rep(NA,npats),
  ndthall=rep(NA, npats),
  ncosts=rep(NA, npats),
  nqalys=rep(NA, npats)
  )

for (i in 1:npats){



  itthip <- PatData[[i]]$int$evtlist$evttime[PatData[[i]]$int$evtlist$evtname=="hfrac"]
  ntthip <- PatData[[i]]$noint$evtlist$evttime[PatData[[i]]$noint$evtlist$evtname=="hfrac"]
  
  ittvert <- PatData[[i]]$int$evtlist$evttime[PatData[[i]]$int$evtlist$evtname%in%c("vfrac1","vfrac2")]
  nttvert <- PatData[[i]]$noint$evtlist$evttime[PatData[[i]]$noint$evtlist$evtname%in%c("vfrac1","vfrac2")]

  ittdeath <- PatData[[i]]$int$evtlist$evttime[PatData[[i]]$int$evtlist$evtname=="death"]
  nttdeath <- PatData[[i]]$noint$evtlist$evttime[PatData[[i]]$noint$evtlist$evtname=="death"]
  
  ExcelData[i,"itthip"] <- itthip
  ExcelData[i,"ntthip"] <- ntthip
  ExcelData[i,c("ittvert1", "ittvert2")] <- ittvert
  ExcelData[i,c("nttvert1", "nttvert2")] <- nttvert
  ExcelData[i,"ittdeath"] <- ittdeath
  ExcelData[i,"nttdeath"] <- nttdeath
  
  ExcelData[i,"ihipcount"] <- PatData[[i]]$int$nhip
  ExcelData[i, "ivertcount"] <- PatData[[i]]$int$nvert
  ExcelData[i,"nhipcount"] <- PatData[[i]]$noint$nhip
  ExcelData[i, "nvertcount"] <- PatData[[i]]$noint$nvert
  ExcelData[i, "idthhip"] <- PatData[[i]]$int$deathhip
  ExcelData[i, "idthall"] <- PatData[[i]]$int$deathother
  ExcelData[i, "ndthhip"] <- PatData[[i]]$noint$deathhip
  ExcelData[i, "ndthall"] <- PatData[[i]]$noint$deathother
  
  ExcelData[i, "icosts"] <- PatData[[i]]$int$thscosts
  ExcelData[i, "iqalys"] <- PatData[[i]]$int$thsqalys
  
  ExcelData[i, "ncosts"] <- PatData[[i]]$noint$thscosts
  ExcelData[i, "nqalys"] <- PatData[[i]]$noint$thsqalys
}

write.csv(ExcelData, file="DSU_PatData.csv")

