#Importing necessary Libraries

library(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.2     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(dplyr)
library(leaflet)
## Warning: package 'leaflet' was built under R version 4.3.2
library(remotes)
## Warning: package 'remotes' was built under R version 4.3.2
library(scales) # For better time axis formatting
## 
## Attaching package: 'scales'
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## The following object is masked from 'package:readr':
## 
##     col_factor
library(prophet)
## Warning: package 'prophet' was built under R version 4.3.2
## Loading required package: Rcpp
## Loading required package: rlang
## 
## Attaching package: 'rlang'
## 
## The following objects are masked from 'package:purrr':
## 
##     %@%, flatten, flatten_chr, flatten_dbl, flatten_int, flatten_lgl,
##     flatten_raw, invoke, splice
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.3.2
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
## 
## The following object is masked from 'package:ggplot2':
## 
##     margin
library(remotes)
# Loading the Dataset
Accident_Data<-read.csv("C:/Users/Anusha Gadgil/Desktop/Accident Analysis filtered.csv")
#Accident_Data

#Performing EDA

# Arrange the data by Accident_Severity column in ascending order to analyse the Data
Arranged_Data <- Accident_Data %>%
  arrange(Accident_Severity)

# To arrange in descending order, use arrange(desc(Accident_Severity))

# View the arranged data
#print(Arranged_Data)

#Performing EDA

count_light_conditions <- Accident_Data %>%
  count(Light_Conditions, sort = TRUE)

# Display the count of each unique light condition
print(count_light_conditions)
##                            Light_Conditions    n
## 1            Daylight: Street light present 4221
## 2   Darkness: Street lights present and lit 1033
## 3             Darkeness: No street lighting  190
## 4 Darkness: Street lights present but unlit   45
## 5         Darkness: Street lighting unknown   33
count_weather_conditions <- Accident_Data %>%
  count(Weather_Conditions, sort = TRUE)

# Display the count of each unique light condition
print(count_weather_conditions)
##            Weather_Conditions    n
## 1     Fine without high winds 4194
## 2  Raining without high winds  824
## 3                       Other  170
## 4     Raining with high winds  106
## 5        Fine with high winds   67
## 6                     Unknown   66
## 7  Snowing without high winds   56
## 8                 Fog or mist   27
## 9     Snowing with high winds    8
## 10                               4

#Calculating the Average speed limit and police response time

cleaned_speed <- Accident_Data$Speed_limit[!is.na(Accident_Data$Speed_limit)]
average_speed_limit <- mean(cleaned_speed)
average_speed_limit
## [1] 37.64216
cleaned_police_response <- Accident_Data$Police_Force[!is.na(Accident_Data$Police_Force)]
average_police_response <- mean(cleaned_police_response)
average_police_response
## [1] 30.65954

#Number of Vehicles Against accident severity

ggplot(Accident_Data, aes(factor(Number_of_Vehicles), fill = factor(Accident_Severity))) +
  geom_bar(position = "dodge") +
  labs(x = "Number of Vehicles", y = "Count", fill = "Accident Severity") +
  ggtitle("Number of Vehicles vs Accident Severity")

#finding the most recurring coordinates on the map to chalk out which location has the highest accident rate

# Read the CSV file

# Combine Longitude and Latitude columns into a single column for ease of Analysis
combined_coordinates <- paste(Accident_Data$Longitude, Accident_Data$Latitude, sep = "_")

# Counting the occurances of each pairs
coordinate_counts <- table(combined_coordinates)

# Find the most recurring coordinate pairs
most_common_coordinates <- names(sort(coordinate_counts, decreasing = TRUE))[1:10]  # Change '5' for more or fewer top values

# Display the most recurring coordinate pairs
most_common_coordinates
##  [1] "-0.192717_51.256565" "-0.199881_51.589677" "-0.023239_51.518399"
##  [4] "-0.174698_51.493966" "-0.199885_51.589587" "-0.971986_51.413385"
##  [7] "-0.975703_51.407933" "-1.023294_52.897333" "-1.109063_52.99186" 
## [10] "-1.170037_51.885847"
# Provided latitude and longitude coordinates
coordinates <- c("-0.192717_51.256565", "-0.199881_51.589677", "-0.023239_51.518399",
                  "-0.174698_51.493966", "-0.199885_51.589587", "-0.971986_51.413385",
                  "-0.975703_51.407933", "-1.023294_52.897333", "-1.109063_52.99186",
                  "-1.170037_51.885847")

# Split the coordinates into separate Longitude and Latitude columns
split_coordinates <- strsplit(coordinates, "_")
Longitude <- as.numeric(sapply(split_coordinates, `[`, 1))
Latitude <- as.numeric(sapply(split_coordinates, `[`, 2))

# Create a data frame with coordinates
data <- data.frame(longitude = Longitude, latitude = Latitude)

# Create a leaflet map
my_map <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(data = data, lng = ~longitude, lat = ~latitude,
                   color = "red", radius = 5) %>%
  setView(lng = mean(Longitude), lat = mean(Latitude), zoom = 8) %>%
  addProviderTiles("Stamen.TonerLite")  # Other map tile providers can be used here

# Display the interactive map
my_map

\[ Conclusion: \text{Maximum Accidents Occur in London.} \]

#remotes::install_version("htmltools", version = "0.5.7", repos = "https://cran.r-project.org")
#remove.packages("htmltools")

#Plotting values to see what time of the day has maximum accidents

# Load required libraries
library(ggplot2)
library(scales) # For better time axis formatting
options(repr.plot.width = 15, repr.plot.height = 3)

# Read the data (replace 'file_path.csv' with your actual file path)
data <- read.csv("C:/Users/Anusha Gadgil/Desktop/Accident Analysis filtered.csv")

data$Time <- as.POSIXct(data$Time, format = "%H:%M:%S")
data <- data[complete.cases(data), ]

# Create the scatter plot
plot <- ggplot(data, aes(x = Time, y = Accident_Severity)) +
  geom_point(size = 0.8, alpha = 4, color = "red") +
  labs(title = "Accident Severity vs Time of Day", x = "Time of Day", y = "Accident Severity") +
  theme_minimal() +
  scale_x_datetime(labels = date_format("%H:%M"), breaks = date_breaks("2 hours")) +
  scale_y_continuous(breaks = seq(1, 3, by = 1))

# Render the plot
print(plot)

\[ Conclusion: \text{Most Accidents occur in the Day and Night time.} \]

#Transforming the Data from Categorical data to Numerical Data where 5 is for the best conditions and 1 for the worst conditions(One Hot Encoding) to feed values to the model

library(dplyr)

# Read the CSV file
data<-read.csv("C:/Users/Anusha Gadgil/Desktop/Accident Analysis filtered.csv")

# Perform transformations for Road_Surface_Conditions
data <- data %>%
  mutate(Road_Surface_Conditions_Numeric = case_when(
    Road_Surface_Conditions == "Dry" ~ 5,
    Road_Surface_Conditions == "Snow" ~ 4,
    Road_Surface_Conditions == "Wet/Damp" ~ 3,
    Road_Surface_Conditions == "Frost/Ice" ~ 2,
    Road_Surface_Conditions == "Flood (Over 3cm of water)" ~ 1,
    TRUE ~ NA_integer_
  ))

# Perform transformations for Weather_Conditions
data <- data %>%
  mutate(Weather_Conditions_Numeric = case_when(
    Weather_Conditions == "Fine without high winds" ~ 7,
    Weather_Conditions == "Fine with high winds" ~ 6,
    Weather_Conditions == "Fog or mist" ~ 5,
    Weather_Conditions == "Raining with high winds" ~ 4,
    Weather_Conditions == "Raining without high winds" ~ 3,
    Weather_Conditions == "Snowing without high winds" ~ 2,
    Weather_Conditions == "Snowing with high winds" ~ 1,
    TRUE ~ NA_integer_
  ))

# Perform transformations for Light_Conditions
data <- data %>%
  mutate(Light_Conditions_Numeric = case_when(
    Light_Conditions == "Darkness: Street lighting unknown" ~ 1,
    Light_Conditions == "Darkeness: No street lighting" ~ 2,
    Light_Conditions == "Daylight: Street light present" ~ 3,
    Light_Conditions == "Darkness: Street lights present but unlit" ~ 4,
    Light_Conditions == "Darkness: Street lights present and lit" ~ 5,
    TRUE ~ NA_integer_
  ))

# Removing rows with NA values
data_cleaned <- na.omit(data[c("Speed_limit", "Light_Conditions_Numeric", "Weather_Conditions_Numeric", "Road_Surface_Conditions_Numeric", "Accident_Severity")])

# Saving the cleaned data to a new CSV file
write.csv(data_cleaned, "processed_data_cleaned.csv", row.names = FALSE)

#I picked the Random Forest Algorithm

library(randomForest)


# Read the CSV file
data<-read.csv("C:/Users/Anusha Gadgil/Desktop/processed_data_cleaned.csv")
data<-na.omit(data[c("Speed_limit", "Light_Conditions_Numeric", "Weather_Conditions_Numeric", "Road_Surface_Conditions_Numeric", "Accident_Severity")])
# Check the structure of your data
#str(data)
data$Road_Surface_Conditions_Numeric <- as.numeric(data$Road_Surface_Conditions_Numeric)
data$Weather_Conditions_Numeric <- as.numeric(data$Weather_Conditions_Numeric)
data$Light_Conditions_Numeric <- as.numeric(data$Light_Conditions_Numeric)

# Splitting data into training and testing sets ( 70-30 split)
set.seed(123)
train_indices <- sample(1:nrow(data), 0.7 * nrow(data))
train_data <- data[train_indices, ]
test_data <- data[-train_indices, ]

# Define predictor variables and target variable
predictors <- c("Speed_limit", "Light_Conditions_Numeric", "Weather_Conditions_Numeric", "Road_Surface_Conditions_Numeric")
target <- "Accident_Severity"
# Train the random forest model
model <- randomForest(as.factor(Accident_Severity) ~ ., data = train_data[, c(predictors, target)])

# Summarizing the trained model
print(model)
## 
## Call:
##  randomForest(formula = as.factor(Accident_Severity) ~ ., data = train_data[,      c(predictors, target)]) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 13.75%
## Confusion matrix:
##   1 2    3  class.error
## 1 0 0   19 1.0000000000
## 2 0 0  486 1.0000000000
## 3 0 3 3187 0.0009404389
# Predict using the test set
predictions <- predict(model, newdata = test_data)

# Evaluate the models accuracy
accuracy <- mean(predictions == test_data$Accident_Severity)
print(paste("Accuracy:", round(accuracy * 100, 2), "%"))
## [1] "Accuracy: 87.69 %"

\[ Conclusion: \text{The weather,road,lighting and speed conditions play a vital role in severe accidents} \]

var_importance <- importance(model)
var_importance_df <- data.frame(Variables = rownames(var_importance), Importance = var_importance[, 1])

library(ggplot2)
# Creating a bar plot for variable importance
ggplot(var_importance_df, aes(x = reorder(Variables, Importance), y = Importance)) +
  geom_bar(stat = "identity", fill = "skyblue", alpha = 0.7) +
  coord_flip() +
  labs(title = "Variable Importance Plot",
       x = "Variables",
       y = "Importance") +
  theme_minimal() +
  theme(axis.text.y = element_text(size = 8))

#Performing Time series Analysis on Police response to accidents of different severity to predict how the local authorities will respond to accidents in the near future

#Importing the data
data <- read.csv("C:/Users/Anusha Gadgil/Desktop/Severity.csv")


data <- data %>%
  select(Date, Police_Force) %>%
  rename(ds = Date, y = Police_Force)

# Ensuring 'ds' column is in the correct date format
data$ds <- as.POSIXct(data$ds, format = "%d-%m-%Y ")

# Create and fit the Prophet model
model <- prophet(data)
## Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.
# Create a future dataframe for forecasting (365 days into the future)
future <- make_future_dataframe(model, periods = 365,freq = 'day')

# Making predictions
forecast <- predict(model, future)

# Plotting the forecast
plot(model, forecast)

head(forecast)
##           ds    trend additive_terms additive_terms_lower additive_terms_upper
## 1 2009-01-01 30.45082      0.7665342            0.7665342            0.7665342
## 2 2009-01-02 30.45125      1.0245722            1.0245722            1.0245722
## 3 2009-01-04 30.45209     -1.2338704           -1.2338704           -1.2338704
## 4 2009-01-05 30.45252     -0.7556317           -0.7556317           -0.7556317
## 5 2009-01-06 30.45294     -0.4953444           -0.4953444           -0.4953444
## 6 2009-01-07 30.45337      0.5646680            0.5646680            0.5646680
##       weekly weekly_lower weekly_upper     yearly yearly_lower yearly_upper
## 1 -0.2808559   -0.2808559   -0.2808559  1.0473901    1.0473901    1.0473901
## 2  0.2671887    0.2671887    0.2671887  0.7573835    0.7573835    0.7573835
## 3 -1.4112111   -1.4112111   -1.4112111  0.1773407    0.1773407    0.1773407
## 4 -0.6541415   -0.6541415   -0.6541415 -0.1014902   -0.1014902   -0.1014902
## 5 -0.1293573   -0.1293573   -0.1293573 -0.3659872   -0.3659872   -0.3659872
## 6  1.1762747    1.1762747    1.1762747 -0.6116067   -0.6116067   -0.6116067
##   multiplicative_terms multiplicative_terms_lower multiplicative_terms_upper
## 1                    0                          0                          0
## 2                    0                          0                          0
## 3                    0                          0                          0
## 4                    0                          0                          0
## 5                    0                          0                          0
## 6                    0                          0                          0
##   yhat_lower yhat_upper trend_lower trend_upper     yhat
## 1 -0.7319408   63.99889    30.45082    30.45082 31.21736
## 2  0.1899234   64.01236    30.45125    30.45125 31.47582
## 3 -4.1846724   61.83472    30.45209    30.45209 29.21822
## 4 -3.1060284   64.07564    30.45252    30.45252 29.69689
## 5 -3.5655261   64.56355    30.45294    30.45294 29.95760
## 6 -2.6712786   65.41318    30.45337    30.45337 31.01803

\[ Conclusion: \text{Average Police force at an accident are 30 officers and will continue to be.} \]