## Clear environment rm(list = ls()) ## Set working directory setwd("~/SP/A1") ## Load tidyverse library(tidyverse) ## Additional functions that are useful for type checking # Check if argument is scalar is.scalar <- function(x) is.atomic(x) && length(x) == 1L && !is.character(x) && Im(x) == 0 ## ;; ## --------------------------------------------- ## Q1: -- add your code below ## --------------------------------------------- ## ;; ## 1.1 # NOTE: We assume that the working directory has been set and that # the files are in this directory. # Read files: this will populate Global Environment with accident.data, # burlington and list.dfs files <- list("accident.RData", "burlington.RData", "list.data.frames.RData") files %>% lapply(load, .GlobalEnv) # Select precipitation values and corresponding dates, keep observations that # exceed a precipitation value of 31 burlington.precip <- burlington %>% select(Precipitation, Date) %>% filter(Precipitation > 31) # For each location, we want to summarize each cause. We do this by grouping # by location and applying the 100*mean() function to each cause column. # The observations in cause variables are either 0 or 1. accident.pct <- accident.data %>% group_by(Where.and.What...Location.list..Regular) %>% summarize_at(vars(starts_with("Causes")), funs(100 * mean(.))) ## 1.2 # Create dataframe that for each hour of the day contains the average, # sample variance, minimum and maximum precipitation. burlington.hour <- burlington %>% group_by(Hour) %>% summarize(precip.mean = mean(Precipitation), precip.var = var(Precipitation), precip.min = min(Precipitation), precip.max = max(Precipitation)) ## 1.3 # NOTE: Despite the title, in the description there is no mention of having to # save the resulting figure. So we have not done it. # Create auxiliary dataframe containing the lower and upper bounds of the # 95% normal based confidence intervals for the mean. We compute the # statistics for each hour. burlington.precip.ci <- burlington %>% group_by(Hour) %>% summarize(n = n(), mean = mean(Precipitation), std = sd(Precipitation)) %>% mutate(error = 1.96 * std / sqrt(n)) %>% mutate(lower.ci = mean - error, upper.ci = mean + error) # Make plot using geom_point (mean) and geom_errorbar (confidence bounds) theme_update(plot.title = element_text(hjust = 0.5)) ggplot(data = burlington.precip.ci) + geom_point(mapping = aes(x = Hour, y = mean), size = 3, shape = 16) + geom_errorbar(mapping = aes(x = Hour, ymin = lower.ci, ymax = upper.ci)) + ylab("Mean precipitation") + ggtitle("Average precipitation for each hour of the day in Burlington") ## 1.4 # Answer: A # df <- left_join(df.1, df.2, by = key) ## 1.5 # Append dataframes in a list (row-wise) # bind_rows is from dplyr df.rbinded <- bind_rows(list.dfs) stopifnot(dim(df.rbinded) == c(75, 5)) ## ;; ## ------------------------------------------- ## Q2: -- add your code below ## ------------------------------------------- ## ;; ## 2.1 rPareto <- function(n = 1000, alpha = 1, beta = 1) { # Draws random samples from a Pareto distribution using # Inverse Transform Sampling. # # Args: # n: Number of samples to be drawn (positive scalar). # alpha: Shape parameter (positive scalar). # beta: Scale parameter (positive scalar). # # Returns: # Samples drawn from Pareto distribution. # # Notes: # CDF of Pareto: F(x) = 1 - (beta / x) ^ alpha, # for alpha > 0, beta > 0 and x > beta # x = beta / (1 - u) ^ (1 / alpha) # we could have used the fact that (1 - u) ~ U. # Argument checking stopifnot(is.scalar(n), is.scalar(alpha), is.scalar(beta), n > 0, alpha > 0, beta > 0) # Generate n random uniform samples u <- runif(n) # Apply transformation (see Notes) x <- beta / (1 - u) ^ (1 / alpha) return(x) } # Function call: we can use the values we set as default, i.e # n = 1000, alpha = 1, beta = 1 samples.pareto <- rPareto() # is equivalent to: samples.pareto <- rPareto(1000, 1, 1) ## 2.2 rRayleigh <- function(n = 1000, sc = 1) { # Draws random samples from a Rayleigh distribution using # Inverse Transform Sampling. # # Args: # n: Number of samples to be drawn (positive scalar). # sc: Scale parameter (positive scalar). # # Returns: # Samples drawn from Rayleigh distribution. # # Notes: # CDF of Rayleigh: F(x) = 1 - exp(-x ^ 2 / (2 * sc ^ 2)), for sc > 0 # x = sc * sqrt(-2 * log(1 - u)) # we could have used the fact that (1 - u) ~ U. # Argument checking stopifnot(is.scalar(n), is.scalar(sc), n > 0, sc > 0) # Generate n random uniform samples u <- runif(n) # Apply transformation (see Notes) x <- sc * sqrt(-2 * log(1 - u)) return(x) } # Function call: we can use the default values, i.e. # n = 1000, sc = 1 samples.rayleigh <- rRayleigh() # is equivalent to: samples.rayleigh <- rRayleigh(1000, 1) ## 2.3 rgev <- function(n = 1000, mu = 0, sc = 1, xi = 1, tol.xi.limit = 5e-2) { # Draws random samples from a Generalized Extreme Value (GEV) # distribution using Inverse Transform Sampling. # # Args: # n: Number of samples to be drawn (positive scalar). # mu: Location parameter (scalar). # sc: Scale parameter (positive scalar). # xi: Shape parameter (scalar). # tol.xi.limit: Tolerance factor for xi (positive scalar). # # Returns: # Samples drawn from GEV. # # Notes: # Simulating from a GEV(mu, sc, xi), for sc > 0 # - if xi == 0 or within tolerance: # x = mu - sc * log(-log(u)) # - else: # x = mu + sc / xi * ((-log(u)) ^ -xi - 1) # Argument checking stopifnot(is.scalar(n), is.scalar(mu), is.scalar(sc), is.scalar(xi), is.scalar(tol.xi.limit), n > 0, sc > 0, tol.xi.limit > 0) # Generate n random uniform samples u <- runif(n) if (abs(xi) < tol.xi.limit) { x <- mu - sc * log(-log(u)) } else { x <- mu + sc / xi * ((-log(u)) ^ -xi - 1) } return(x) } # Function call: we can use the default values for n, mu and sc, i.e # n = 1000, mu = 0, sc = 1 samples.gev.1 <- rgev(xi = 0) samples.gev.2 <- rgev(xi = 1) samples.gev.3 <- rgev(xi = -0.5) ## 2.4 rbeta.rs <- function(n = 1000, alpha = 2, beta = 1) { # Draws random samples from a Beta distribution # using Rejection Sampling with U[0, 1] proposal. # # Args: # n: Number of samples to be drawn (positive scalar). # alpha: Shape parameter (positive scalar). # beta: Shape parameter (positive scalar). # # Returns: # Samples drawn from beta. # # Notes: # Simulating from a Beta(alpha, beta), for # x \in [0, 1], alpha > 0, beta > 0: # - Beta(alpha, beta) \propto x ^ (alpha - 1) * (1 - x) ^ (beta - 1) # - if alpha == 1, beta == 1: # We have the standard Uniform distribution because the unnormalized # distribution is proportional to 1. In this case, the target and # the proposal distributions are the same, with C = 1. We can thus # simulate directly from the proposal and accept every sample. # - if alpha, beta > 1 or at most one is equal to 1: # The mode occurs for (alpha - 1) / (alpha + beta - 2), and so # we use this to compute C. # - if alpha < 1 and/or beta < 1: # The distribution is unbounded on either x = 0, x = 1 or both. # We need: alpha >= 1, beta >= 1 (to be used in argument checking) # In what follows, we assume we do not have access to the normalizing # constant. # Argument checking stopifnot(is.scalar(n), is.scalar(alpha), is.scalar(beta), n > 0) if (!(alpha >= 1 & beta >= 1)){ # print message for invalid schemes stop("Invalid parameter values") } if ((alpha == 1) & (beta == 1)) { return(runif(n)) # generate standard Uniform distributed samples } else { # Perform Rejection Sampling mode <- (alpha - 1) / (alpha + beta - 2) # compute mode C <- mode^(alpha - 1) * (1 - mode) ^ (beta - 1) # scaled beta eval. at mode samples <- numeric(n) # preallocate memory for (i in 1:n) { while (TRUE) { # keep sampling if sample has been rejected x <- runif(1, 0, 1) # sample x y <- runif(1, 0, C) # sample y fx <- x ^ (alpha - 1) * (1 - x) ^ (beta - 1) # evaluate function at x if (y <= fx) { # accept sample samples[i] <- x break } } } return(samples) } } # Function call: using default parameters, i.e. n = 1000, alpha = 2, beta = 1 samples.beta <- rbeta.rs() # Checking answer # a <- 2 # b <- 1 # curve(dbeta(x, a, b), lty = 3) # hist(rbeta.rs(n = 10000, a, b), freq = FALSE, add = TRUE) ## ;; ## ------------------------------------------- ## Q3: -- add your code below ;; ## ------------------------------------------- ## ;; ## 3.1 # Notes: # Data has been loaded before into accident.data (Q1.1). # Since there is no other information telling us otherwise, we will assume the # time standard UTC (Universal Time, Coordinated). # We will be using lubridate for handling datetimes. The smallest unit # of our model is hours - we will ignore minutes/seconds when constructing # datetimes. # Convert timehour to datetime - smallest unit of time is going to be hours. GetDatetime <- function(timehour, origin) floor(timehour) %>% lubridate::hours(.) + origin # Given datetime, fetch hours as numeric GetHour <- function(datetime) lubridate::hour(datetime) ntotal <- dim(accident.data)[1] # total number of accidents # Fetch our first date because Timehour is the number of hours elapsed since # this date origin <- accident.data$Where.and.What...Date..Period..Day[1] # Generate dataframe with relative frequency of traffic accidents (hourly) hour.frequency.data <- accident.data %>% mutate(hour = GetDatetime(Timehour, origin) %>% GetHour()) %>% group_by(hour) %>% summarize(rel.freq = n() / ntotal) # Generate pdf file with the circular histogram of accident occurence (hourly) pdf(file = "s1740192.circ.hist.pdf", height = 10, width = 10) p <- ggplot(data = hour.frequency.data, aes(x = hour, y = rel.freq)) + geom_bar(width = 1, colour = "gold", alpha = 0.6, stat = "identity") + scale_x_continuous("", breaks = seq(0, 23), labels = seq(0, 23)) + coord_polar(theta = "x", start = -pi/24, direction = 1) + theme(plot.title = element_text(face = "bold", size = 16), axis.title.y = element_text(face = "bold", size = 15), axis.text = element_text(face = "bold", colour = "grey40", size = 14)) + labs(title = "Circular histogram of accident occurrence (hourly)", y = "Relative frequency") p dev.off() ## 3.2 ComputeEffects <- function(datetime) { # Compute matrix of effects given datetimes. # # Args: # datetime: Sequence of datetimes (POSIXt). # # Returns: # Matrix of effects. # # Notes: # A vector of ones has been included in the first column so that # we can compute the log-intensity with one multiplication, # see LogIntensity. # Argument checking stopifnot(inherits(datetime, "POSIXt")) # Compute hourly effects hours <- lubridate::hour(datetime) Bh <- as.numeric((hours >= 6) & (hours <= 18)) # Compute daily effects weekdays <- lubridate::wday(datetime) # decimal number (01-07, Sunday is 1) Bd <- as.numeric((weekdays > 1) & (weekdays < 7)) # Compute seasonal effects months <- lubridate::month(datetime) Bs <- as.numeric((months == 3) | (months == 4)) # March and April return(cbind(1, Bh = Bh, Bd = Bd, Bs = Bs)) } # log-intensity function LogIntensity <- function(effects, beta) effects %*% beta llik.nhpp <- function(beta, Timehour = NULL, origin = NULL, effects.obs = NULL, effects.all = NULL) { # Computes negative log-likelihood of a non-homogeneous Poisson point process # with log-intensity function given by LogIntensity. # # Args: # beta: Model parameters (numeric). # Timehour: (Mode 1) Sequence of timehours (numeric). # origin: (Mode 1) Start date. # effects.obs: (Mode 2) Precomputed matrix of effects for observations. # effects.all: (Mode 2) Precomputed matrix of effects for all hourly # datetimes within the period under consideration. # Returns: # Negative log-likelihood. # # Notes: # Operation modes # (1) If Timehour and origin are provided: # - compute effects.obs and effects.all. # (2) elif effects.obs and effects.all are provided: # - run optimized version, because there is no need to generate these. # Operation mode 1 only has been included to satisfy the requirement # stated in the assignment. It is wasteful to compute the effects every # time this function is evaluated, since the effects do not change with # beta. # Argument checking stopifnot(is.numeric(beta)) # Check if mode 1 needs to be run if (is.numeric(Timehour) & inherits(origin, "Date")) { # Get the corresponding sorted datetimes datetime.obs <- sort(GetDatetime(Timehour, origin)) datetime.all <- seq(datetime.obs[1], datetime.obs[length(datetime.obs)], by = "hours") # Compute the effects effects.obs <- ComputeEffects(datetime.obs) effects.all <- ComputeEffects(datetime.all) } else if (!is.matrix(effects.obs) | !is.matrix(effects.all)) { stop("Invalid function call.") } # Check possible dimension mismatch stopifnot(dim(effects.obs)[2] == length(beta), dim(effects.all)[2] == length(beta)) # Compute negative log likelihood: sum(exp(llam.all)) - sum(llam.obs) llam.obs <- LogIntensity(effects.obs, beta) llam.all <- LogIntensity(effects.all, beta) nllik <- sum(exp(llam.all)) - sum(llam.obs) return(nllik) } # Precompute the effects for efficiency # origin and ntotal are variables from Q3.1 datetime.obs <- sort(GetDatetime(accident.data$Timehour, origin)) datetime.all <- seq(datetime.obs[1], datetime.obs[ntotal], by = "hours") effects.obs <- ComputeEffects(datetime.obs) effects.all <- ComputeEffects(datetime.all) # Fit the point process model by minimizing the negative log-likelihood # Note: We have tested multiple random restarts and Nelder-Mead as well. # These converge to roughly the same point. beta.init <- rep(0, 4) # initial values for beta model <- optim(par = beta.init, fn = llik.nhpp, effects.obs = effects.obs, effects.all = effects.all, method = "BFGS", control = list(maxit = 10000)) stopifnot(model$convergence == 0) beta.opt <- model$par # We assume that by last year, it is meant the full year of 2016 and not the # last 12 months. last.year.datetime <- lubridate::ymd("2016-01-01", tz = "UTC") + c(0:(366*24)) * lubridate::hours(1) # seq of POSIXt last.year.datetime <- last.year.datetime[-length(last.year.datetime)] effects.last.year <- ComputeEffects(last.year.datetime) last.year.intensity <- data.frame(datetime = as.Date(last.year.datetime), intensity = LogIntensity(effects.last.year, beta.opt) %>% exp()) # Generate pdf file with plot displaying the MLE intensity in 2016 pdf(file = "s1740192.nhpp.intensity.pdf", height = 8, width = 16) p <- ggplot(data = last.year.intensity, aes(x = datetime, y = intensity)) + geom_line(linetype = "dashed") + scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") + theme(plot.title = element_text(face = "bold", size = 16), axis.title.y = element_text(face = "bold", size = 15), axis.text = element_text(face = "bold", colour = "grey40", size = 14), axis.text.x = element_text(angle = 60, hjust = 1)) + labs(title = "MLE Intensity (2016)", y = "Intensity", x = "") p dev.off() ## 3.3 PredictIncidents <- function(datetime.period, beta, k = 0:9) { # Given beta, computes the probability of observing k_i incidents during the # period of time given by datetime.period. # # Args: # datetime.period: Sequence with two datetimes, start and end (POSIXt). # beta: Model parameters (numeric). # k: Sequence with the number of incidents (numeric). # # Returns: # Prediction probabilities - one for each element in k (dataframe). # Argument unpacking and checking stopifnot(inherits(datetime.period, "POSIXt"), length(datetime.period) == 2, is.numeric(beta), is.numeric(k)) datetime.start <- datetime.period[1] datetime.end <- datetime.period[2] stopifnot(datetime.start < datetime.end) # Generate datetimes (hourly) datetime <- seq(datetime.start, datetime.end, by = "hours") # Compute effects and check that dimensions with beta match effects <- ComputeEffects(datetime) stopifnot(dim(effects)[2] == length(beta)) # Compute predictions sum.lam <- sum(exp(LogIntensity(effects, beta))) prob.estimates <- exp(-sum.lam) * sum.lam ^ k / factorial(k) return(data.frame(k = k, prob.estimates = prob.estimates)) } FindFirstWday <- function(year, month, wday){ # Determine the first weekday of a given year and month. # # Args: # year: Year under consideration (scalar). # month: Month under consideration (scalar). # wday: Day of the week - 1-7, Sunday is 1 (scalar). # # Returns: # Date of the first wday (POSIXt), UTC. # Argument checking stopifnot(is.scalar(year), is.scalar(month), is.scalar(wday), year >= 1970, year <= 9999, month > 0, month < 13, wday > 0, wday < 8) # Get first date as string first.date <- sprintf("%s-%s-01", year, month) # Determine first seven days first.week <- lubridate::ymd(first.date, tz = "UTC") + c(0:6) * lubridate::days(1) # Fetch corresponding wday first.wday <- first.week[lubridate::wday(first.week) == wday] return(first.wday) } # Generate periods dt <- vector(mode = "list", length = 4) # 09.00-15.00 of a Monday in December 2017 (first) dt[[1]] <- FindFirstWday(2017, 12, 2) + lubridate::hours(c(9, 15)) # 09.00-15.00 of a Sunday in December 2017 (first) dt[[2]] <- FindFirstWday(2017, 12, 1) + lubridate::hours(c(9, 15)) # 18.00-20.00 of a Friday in April 2016 (first) dt[[3]] <- FindFirstWday(2016, 4, 6) + lubridate::hours(c(18, 20)) # First week of April 2018 # This can mean the first seven days of the month or # the week from first Sunday to the following Saturday (inclusive). # We have used first Sun - Sat (incl.). In this particular case of April 2018, # both interpretations match because the first day is Sun. dt[[4]] <- FindFirstWday(2018, 4, 1) + lubridate::days(c(0, 6)) # Generate the list with the estimates prob.estimates <- lapply(dt, PredictIncidents, beta = beta.opt) stopifnot(is.list(prob.estimates), length(prob.estimates) == 4) ## ;; ## ------------------------------------------- ## Q4: -- add your code below;; ## ------------------------------------------- ## ;; ## 4.1 llik.gpd <- function(par, x, thresh, tol.xi.limit = 5e-2){ # Computes negative log-likelihood of sc and xi of a generalised Pareto # distribution function. # # Args: # par: Sequence with values log(sc), xi (numeric). # x: Sequence of observations (numeric). # thresh: Value at which observations become excesses (scalar). # tol.xi.limit: Tolerance factor for xi (positive scalar). # # Returns: # Negative log-likelihood. # Argument checking stopifnot(is.numeric(par), length(par) == 2, is.numeric(x), is.scalar(thresh), is.scalar(tol.xi.limit), tol.xi.limit > 0) # Unpack parameters log.sc <- par[1] xi <- par[2] sc <- exp(log.sc) # Fetch values that exceed threshold and compute excesses y <- x[x > thresh] - thresh n <- length(y) if (abs(xi) < tol.xi.limit) { return(n * log.sc + sum(y) / sc) # nllik of exponential with lam = 1 / sc } else { # nllik when xi outside tolerance range return(n * log.sc + (1 + 1 / xi) * sum(log(pmax(0, 1 + (xi/sc) * y)))) } } ## 4.2 u <- quantile(burlington$Precipitation, seq(0.85, 0.99, by = 0.01)) # For each quantile, compute mle by minimization of the negative # log-likelihood function (Q4.1) # we could have used a two-step optimization procedure as done in Q4.3, but # the values are going to be roughly the same model <- sapply(u, function(u) optim(par = rep(5, 2), fn = llik.gpd, x = burlington$Precipitation, thresh = u, method = "BFGS")) stopifnot(model["convergence",] == 0) # check convergence for all quantiles mle.u <- as.matrix(bind_rows(model["par",])) %>% t() # unpack results mle.u[, 1] <- exp(mle.u[, 1]) # log.sc -> sc colnames(mle.u) <- c("hat(sigma)[u]", "hat(xi)[u]") stopifnot(is.matrix(mle.u), dim(mle.u) == c(15, 2)) # Generate plot and save figure to pdf pdf(file = "s1740192.stability.pdf", height = 8, width = 16) p <- mle.u %>% cbind(u = u, .) %>% as.tibble() %>% gather("Parameter", "value", 2:3) %>% ggplot(aes(x = u, y = value))+ geom_point(size = 3) + facet_grid(. ~ Parameter, labeller = label_parsed) + geom_smooth(method = "auto") + theme(plot.title = element_text(face = "bold", size = 16), axis.title = element_text(face = "bold", size = 15), axis.text = element_text(face = "bold", colour = "grey40", size = 14), strip.text.x = element_text(size = 14)) + scale_x_continuous("u", limits = c(1, 8), breaks = seq(1, 8), labels = seq(1, 8)) + labs(title = paste("Precipitation in Burlington:", "MLE of Generalized Pareto for different thresholds")) p dev.off() ## 4.3 ret.level <- function(x, thresh, ret.period, opt.combined = TRUE){ # Computes return level point estimates based on MLE of generalised Pareto # distribution function. # # Args: # x: Sequence of observations (numeric) # thresh: Value at which observations become excesses (scalar). # ret.period: Sequence of return periods (numeric). # opt.combined: If TRUE, run Nelder-Mead first and use the optimal # values as initialization for BFGS. Otherwise, use BFGS only. # # Returns: # Point estimates of return level for each element in ret.period. # Argument checking stopifnot(is.numeric(x), is.scalar(thresh), is.numeric(ret.period)) # Determine MLE of zeta zeta <- sum(x > thresh) / length(x) # n_excesses / n_observations # Run optimizer and make sure it converged par.init = rep(5, 2) if (opt.combined) { model <- optim(par = par.init, fn = llik.gpd, x = x, thresh = thresh, method = "Nelder-Mead", control = list(maxit = 10000)) stopifnot(model$convergence == 0) par.init <- model$par } model <- optim(par = par.init, fn = llik.gpd, x = x, thresh = thresh, method = "BFGS") stopifnot(model$convergence == 0) # Unpack results mle <- model$par sc = exp(mle[1]) xi <- mle[2] # Compute return level return(thresh + sc / xi * ((ret.period * zeta) ^ xi - 1)) } precip.spring <- burlington %>% filter(Spring == 1) %>% select(Precipitation) %>% unlist(use.names = FALSE) u <- quantile(precip.spring, seq(0.85, 0.99, by = 0.01)) ret.period <- c(100, 500, 1000, 10000) x.level <- sapply(u, function(u) ret.level(x = precip.spring, thresh = u, ret.period = ret.period)) pdf(file = "s1740192.ret.levels.pdf", height = 8, width = 16) p <- x.level %>% cbind(ret.period = ret.period, .) %>% as.tibble() %>% gather("Quantile", "value", 2:16) %>% ggplot(aes(x = ret.period, y = value, group = Quantile, colour = Quantile)) + geom_point(size = 3) + geom_line() + scale_x_log10(breaks = c(1, 5, 10, 50, 100, 500, 1000, 10000)) + theme(plot.title = element_text(face = "bold", size = 16), axis.title = element_text(face = "bold", size = 15), axis.text = element_text(face = "bold", colour = "grey40", size = 14), legend.title = element_text(face = "bold", size = 12), legend.key.size = unit(0.6, "cm"), strip.text.x = element_text(size = 14)) + labs(title = "Precipitation in Burlington (Spring): MLE Return level", x = "Return Period", y = "Return Level") p dev.off() ## ------------------------------------------------