options(warn=-1)

#load the data files 
council.mth.data <- read.csv("~/Desktop/Project 4/Data/council.mth.data.csv")
natl.yr.mth.data <- read.csv("~/Desktop/Project 4/Data/natl.yr.mth.data.csv")

#extract the time series for the homeless applications by months 
df.app<-natl.yr.mth.data[c(10:201),c(3)]
ts.app <- ts(df.app, start=c(2003, 1), end=c(2018, 12), frequency=12) 

# set up dlm model and estimate the parameters-application 
install.packages('dlm',repos = "http://cran.us.r-project.org")
## 
##   There is a binary version available but the source version is
##   later:
##     binary source needs_compilation
## dlm  1.1-4  1.1-5              TRUE
## installing the source package 'dlm'
library(dlm)
lapp<-log(ts.app)
dlmApp <- dlmModPoly() + dlmModSeas(12)

buildApp <- function(x) {
  diag(W(dlmApp))[2:3] <- exp(x[1:2])
  V(dlmApp) <- exp(x[3])
  return(dlmApp)
}

(fit.app <- dlmMLE(lapp, parm = rep(0, 3), build = buildApp))$conv 
## [1] 0
dlmApp <- buildApp(fit.app$par)
drop(V(dlmApp))
## [1] 0.006912174
diag(W(dlmApp))[2:3]
## [1] 0.0023064584 0.0002996839
#plot the actual trend, smoothed trend and seasonal noise-application  
appSmooth <- dlmSmooth(lapp, mod = dlmApp)
x <- cbind(lapp, dropFirst(appSmooth$s[, c(1, 3)]))
colnames(x) <- c("Applications", "Trend", "Seasonal")
plot(x, type = "o", main = "Homeless Applications in Scotland")

#........................................................................................

#extract the time series for the homeless applications per 100,000 people by months 
app.pop<-natl.yr.mth.data$Homeless.app/natl.yr.mth.data$pop*100000
ts.app.pop <- ts(app.pop, start=c(2003, 1), end=c(2018, 12), frequency=12) 

# set up dlm model and estimate the parameters- appications per 100,000 people 
lapp.pop<-log(ts.app.pop)
dlmAppPop <- dlmModPoly() + dlmModSeas(12)

buildAppPop <- function(x) {
  diag(W(dlmAppPop))[2:3] <- exp(x[1:2])
  V(dlmAppPop) <- exp(x[3])
  return(dlmAppPop)
}

(fit.app.pop <- dlmMLE(lapp.pop, parm = rep(0, 3), build = buildAppPop))$conv 
## [1] 0
dlmAppPop <- buildAppPop(fit.app.pop$par)
drop(V(dlmAppPop))
## [1] 0.006826914
diag(W(dlmAppPop))[2:3]
## [1] 0.0022726643 0.0002936524
#plot the actual trend, smoothed trend and seasonal noise- appications per 100,000 people  
apppopSmooth <- dlmSmooth(lapp.pop, mod = dlmAppPop)
x1 <- cbind(lapp.pop, dropFirst(apppopSmooth$s[, c(1, 3)]))
colnames(x1) <- c("Applications per 100k people", "Trend", "Seasonal")
plot(x1, type = "o", main = "Homeless Applications in Scotland per 100k people")