# ==============================================================================
# Script Name: AirQualityAnalysis.r
# Assignment: Data Analysis (ACCA7022)
# Student Name: Shaidhul Hasan (ID: 2442113)
# Programme: MSc Data and Artificial Intelligence
# ==============================================================================

# 1. DATA IMPORT AND SUMMARY (ILO1) --------------------------------------------
# Load required libraries using pacman for efficiency
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, corrplot, lubridate, car)

# Import the dataset
# Note: Using sep = ";" and dec = "," because this is a European CSV format.
# -200 is defined as the missing value in the UCI documentation.
AirQuality <- read.csv("AirQualityUCI.csv", sep = ";", na.strings = "-200", dec = ",")

# Data Cleaning: Remove empty columns often found in this CSV and drop NA rows
AirQuality <- AirQuality[, 1:15]
AirQuality <- na.omit(AirQuality)

# Display required summary information (Task 1.1)
print("--- Dataset Dimensions ---")
print(dim(AirQuality))

print("--- First Few Rows ---")
print(head(AirQuality))

print("--- Basic Descriptive Statistics ---")
print(summary(AirQuality))


# 2. EXPLORATORY VISUALISATION (ILO3, ILO4) ------------------------------------
# Convert Date and Time strings into a proper DateTime object for time-series
AirQuality$DateTime <- as.POSIXct(paste(AirQuality$Date, AirQuality$Time), 
                                  format="%d/%m/%Y %H.%M.%S")

# Trend 1: Line plot for CO and NO2 levels over time
# Rationale: Line plots are best for identifying temporal trends and cycles.
ggplot(AirQuality, aes(x = DateTime)) +
  geom_line(aes(y = CO.GT., color = "CO(GT)"), alpha = 0.7) +
  geom_line(aes(y = NO2.GT., color = "NO2(GT)"), alpha = 0.7) +
  labs(title = "Time Trends of CO and NO2 Concentrations",
       x = "Date", y = "Concentration") +
  theme_minimal()

# Trend 2: Scatterplot for Temperature vs Benzene
# Rationale: Scatterplots help visualize the correlation between two continuous variables.
ggplot(AirQuality, aes(x = T, y = C6H6.GT.)) +
  geom_point(alpha = 0.3, color = "steelblue") +
  geom_smooth(method = "lm", color = "red") +
  labs(title = "Relationship between Temperature and Benzene",
       x = "Temperature (°C)", y = "Benzene (C6H6)") +
  theme_light()


# 3. CORRELATION ANALYSIS (ILO1, ILO3, ILO4) ----------------------------------
# Calculate correlations between three pollutants and Temperature
pollutants <- AirQuality %>% select(CO.GT., NO2.GT., C6H6.GT., T)
cor_matrix <- cor(pollutants)

# Visualize using a correlogram
corrplot(cor_matrix, method = "color", type = "upper", 
         addCoef.col = "black", tl.col = "black",
         title = "Pollutant Correlation Matrix", mar=c(0,0,1,0))


# 4. HYPOTHESIS TESTING (ILO1, ILO3) ------------------------------------------
# Comparing CO levels under High vs Low Humidity (RH)
# H0: There is no difference in CO levels between High and Low Humidity.
# H1: There is a significant difference in CO levels.
median_rh <- median(AirQuality$RH)
AirQuality$Humidity_Level <- ifelse(AirQuality$RH > median_rh, "High", "Low")

# Using Wilcoxon test as air quality data is often non-normal
wilcox_result <- wilcox.test(CO.GT. ~ Humidity_Level, data = AirQuality)
print(wilcox_result)


# 5. GROUP COMPARISON: SEASONS (ILO1, ILO3, ILO4) ------------------------------
# Define Seasons based on Month
AirQuality$Month <- month(AirQuality$DateTime)
AirQuality$Season <- case_when(
  AirQuality$Month %in% c(12, 1, 2) ~ "Winter",
  AirQuality$Month %in% c(3, 4, 5) ~ "Spring",
  AirQuality$Month %in% c(6, 7, 8) ~ "Summer",
  AirQuality$Month %in% c(9, 10, 11) ~ "Autumn"
)

# FIX: Convert Season to a Factor so R recognizes it as a group
AirQuality$Season <- as.factor(AirQuality$Season)

# Visualise with a Boxplot
ggplot(AirQuality, aes(x = Season, y = NO2.GT., fill = Season)) +
  geom_boxplot() +
  labs(title = "Seasonal Distribution of NO2 Levels",
       y = "NO2 Concentration") +
  theme_bw()

# Statistical Test: ANOVA (with safety check)
if(length(levels(AirQuality$Season)) > 1) {
  anova_test <- aov(NO2.GT. ~ Season, data = AirQuality)
  print(summary(anova_test))
} else {
  print("Notice: Only one season (Spring) detected in this subset. ANOVA requires 2+ seasons to compare.")
}


# 6. QUALITY CHECK -------------------------------------------------------------
# Code is commented and structured for readability as per Task 1.6 requirements.

