# Loading the required packages
library(ggplot2)
library(tidyverse)
library(MASS)

# Clear the workspace
rm(list=ls())


# Set the random seed for reproducibility
set.seed(2023)

# Specify the path to the data file
data_path <- ("D:/BME/PhD/3. félév/Cikkek/International Journal on Geomathematics/Revision 2/VGT3_veszélyes_anyagok_merged_v7_hidromorf_2.csv")

# Read the data from the CSV file
data <- read.csv(file = data_path, dec=".", sep=";", header = TRUE, fileEncoding="ISO-8859-2")

# Convert the phytoplankton status class data to factors with 5 levels: bad, poor, moderate, good and high.
data <- transform(data, FP_osztály=as.factor(FP_osztály))
data$FP_osztály <- factor(data$FP_osztály, levels=c("bad","poor","moderate","good", "high"))

# Convert the phytobenthos status class data to factors with 5 levels: bad, poor, moderate, good and high.
data <- transform(data, FB_osztály=as.factor(FB_osztály))
data$FB_osztály <- factor(data$FB_osztály, levels=c("bad","poor","moderate","good", "high"))

# Convert the macrophytes status class data to factors with 5 levels: bad, poor, moderate, good and high.
data <- transform(data, MF_osztály=as.factor(MF_osztály))
data$MF_osztály <- factor(data$MF_osztály, levels=c("bad","poor","moderate","good", "high"))

# Convert the morphological status class data to factors with 5 levels (from bad-5 to high-1)
data <- transform(data, MORFOLÓGIAI.ÁLLAPOT..validált.=as.factor(MORFOLÓGIAI.ÁLLAPOT..validált.))
data$MORFOLÓGIAI.ÁLLAPOT..validált. <- factor(data$MORFOLÓGIAI.ÁLLAPOT..validált., levels=c("5","4","3","2", "1"))

# Convert the continuity status class data to factors with 5 levels (from bad-5 to high-1)
data <- transform(data, ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált.=as.factor(ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált.))
data$ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált. <- factor(data$ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált., levels=c("5","4","3","2", "1"))

# Convert the hydrological status class data to factors with 5 levels (from bad-5 to high-1)
data <- transform(data, ÁLLAPOTÉRTÉKELÉS.HIDROLÓGIA..validált.=as.factor(ÁLLAPOTÉRTÉKELÉS.HIDROLÓGIA..validált.))
data$ÁLLAPOTÉRTÉKELÉS.HIDROLÓGIA..validált. <- factor(data$ÁLLAPOTÉRTÉKELÉS.HIDROLÓGIA..validált., levels=c("5","4","3","2", "1"))

# Convert the hydromorphological status class data to factors with 5 levels (from bad-5 to high-1)
data <- transform(data, HIDROMORFOLÓGIAI.ÁLLAPOT..EU.szabvány.szerinti.jelölés..validált.=as.factor(HIDROMORFOLÓGIAI.ÁLLAPOT..EU.szabvány.szerinti.jelölés..validált.))
data$HIDROMORFOLÓGIAI.ÁLLAPOT..EU.szabvány.szerinti.jelölés..validált. <- factor(data$HIDROMORFOLÓGIAI.ÁLLAPOT..EU.szabvány.szerinti.jelölés..validált., levels=c("5","4","3","2", "1"))

# Select data from the period 2013-2017
data_VGT3 <- data[data$YEAR %in% c('2013', '2014', '2015', '2016', '2017'),]

# Select a subset of variables for the analysis
data_VGT3_short <-  data_VGT3[,(colnames(data_VGT3) %in% c(
  "Mennyiség.Ammónia.ammónium.nitrogén", # NH4-N
  "Mennyiség.Ásványi.nitrogén", # inorganic N
  "Mennyiség.Biokémiai.oxigénigény..BOI5.", # BOD5
  "Mennyiség.Foszfor..összes.", # total P
  "Mennyiség.Klorid", # chloride
  "Mennyiség.KOIps..permanganátos.kémiai.oxigénigény..FEV.", #COD Mn
  "Mennyiség.Nitrát.nitrogén..NO3.N.", # NO3-N
  "Mennyiség.Nitrit.nitrogén..NO2.N.", # NO2-N
  "Mennyiség.Oldott.szerves.szén..DOC.", # dissolved organic carbon
  "Mennyiség.Ortofoszfát", # orthophosphate
  "Mennyiség.Oxigén..oldott.", # dissolved oxygen
  "Mennyiség.Összes.lebegő.anyag", # suspended solids
  "Mennyiség.Összes.nitrogén", # total N
  "Mennyiség.Összes.szerves.nitrogén..N.ben.", # organic N
  "Mennyiség.Összes.szerves.szén..TOC.", #TOC
  "Mennyiség.Vezetőképesség", # electrical conductivity
  "Mennyiség.Vízhőmérséklet", # water temperature
  "Mennyiség.KOICr..dikromátos.kémiai.oxigénigény..FEV.", # COD Cr
  "Mennyiség.Zavarosság.nefelometriás", # turbidity
  "FP_osztály", # phytoplankton status class
  "FB_osztály", # phytobenthos status class
  "MF_osztály", # macrophytes status class
  "biol_tipus", # river type
  "intagrp", # proportion of intensive agricultural areas on the catchment
  "nont_agrp", # proportion of extensive agricultural areas on the catchment
  "Vegyes.mezőgazdasági.terület.aránya.a.vízgyűjtőn....", # proportion of heterogeneous agricultural areas on the catchment
  "MORFOLÓGIAI.ÁLLAPOT..validált.", # morphologycal status class
  "ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált.", # continuity status class
  "ÁLLAPOTÉRTÉKELÉS.HIDROLÓGIA..validált.", # hydrological status class
  "HIDROMORFOLÓGIAI.ÁLLAPOT..EU.szabvány.szerinti.jelölés..validált." # hydromorphologycal status class
))]


# Calculate the percentage of missing values in each column
sort(apply(apply(data_VGT3_short,2,is.na),2,sum)/nrow(data_VGT3_short))

# Remove variables with more than 50% missing values
data_VGT3_short_2 <- data_VGT3_short[, 0.5 > apply(apply(data_VGT3_short,2,is.na),2,sum)/nrow(data_VGT3_short)]

# Restore the "macrophytes class" column which was removed in the previous line due to missing values
data_VGT3_short_2$MF_osztály <- data_VGT3_short$MF_osztály

# Separate data for each BQE, excluding the others
FB_data <- data_VGT3_short_2[, !(colnames(data_VGT3_short_2) %in% c("FP_EQR", "FP_osztály", "MF_EQR", "MF_osztály"))] # for phytobenthos, excluding macrophytes and phytoplankton
FP_data <- data_VGT3_short_2[, !(colnames(data_VGT3_short_2) %in% c("FB_EQR", "FB_osztály", "MF_EQR", "MF_osztály"))] # for phytoplankton, excluding macrophytes and phytobenthos
MF_data <- data_VGT3_short_2[, !(colnames(data_VGT3_short_2) %in% c("FP_EQR", "FP_osztály", "FB_EQR", "FB_osztály"))] # for macrophytes, excluding phytobenthos and phytoplankton

# Creating a dataset for big rivers in case of phytobenthos and removing irrelevant variables from the the subset of phytobenthos
FB_data_big <-  FB_data[, !(colnames(FB_data) %in% c(
  "Mennyiség.Vezetőképesség", # electrical conductivity
  "Mennyiség.Vízhőmérséklet", # water temperature
  "intagrp", # proportion of intensive agricultural areas on the catchment
  "nont_agrp", # proportion of extensive agricultural areas on the catchment
  "Vegyes.mezőgazdasági.terület.aránya.a.vízgyűjtőn...." # proportion of heterogeneous agricultural areas on the catchment
))]

# Creating a dataset for big rivers in case of phytoplankton and removing irrelevant variables from the the subset of phytoplankton
FP_data_big <- FP_data[, !(colnames(FP_data) %in% c(
  "Mennyiség.Vezetőképesség", # electrical conductivity
  "Mennyiség.Vízhőmérséklet", # water temperature
  "intagrp", # proportion of intensive agricultural areas on the catchment
  "nont_agrp", # proportion of extensive agricultural areas on the catchment
  "Vegyes.mezőgazdasági.terület.aránya.a.vízgyűjtőn...." # proportion of heterogeneous agricultural areas on the catchment
))]


##### FB ##### 

# Creating the type "highland small watercourses" in case of phytobenthos by subsetting the data and selecting the 5 most 
# important variables based on the previously made random forest model.
FB_123_short <-  FB_data[FB_data$biol_tipus%in%c(1,2,3),(colnames(FB_data)%in%c(
  "FB_osztály", # phytobenthos status class
  "Mennyiség.Biokémiai.oxigénigény..BOI5.", # BOD5
  "nont_agrp", # proportion of extensive agricultural areas on the catchment
  "Mennyiség.Oxigén..oldott.", # dissolved oxygen
  "Mennyiség.Vezetőképesség", # electrical conductivity
  "Mennyiség.Összes.szerves.nitrogén..N.ben."))] # organic N

# Removing empty status classes (with no data)
FB_123_short$FB_osztály <- factor(FB_123_short$FB_osztály, levels=c("bad", "poor", "moderate","good", "high")[c("bad", "poor", "moderate","good", "high")%in%unique(FB_123_short$FB_osztály)])


# Classifying status classes into two classes: good or better and moderate or worse
FB_123_short$FB_osztály_bin <- NA
FB_123_short$FB_osztály_bin[FB_123_short$FB_osztály%in%c("poor","moderate")] <- 0
FB_123_short$FB_osztály_bin[!(FB_123_short$FB_osztály%in%c("poor","moderate"))] <- 1
FB_123_short$FB_osztály_bin[is.na(FB_123_short$FB_osztály)] <- NA

# table(FB_123_short$FB_osztály_bin,FB_123_short$FB_osztály)

# Performing logistic regression on the data of highland small watercourses with the 5 chosen variables
mod_test <- glm(FB_osztály_bin~Mennyiség.Biokémiai.oxigénigény..BOI5.+ #BOD5
                  nont_agrp+ # proportion of extensive agricultural areas on the catchment
                  Mennyiség.Oxigén..oldott.+ # dissolved oxygen
                  Mennyiség.Vezetőképesség+ # electrical conductivity
                  Mennyiség.Összes.szerves.nitrogén..N.ben., # organic N
                data=FB_123_short,
                family=binomial)

# Printing the summary of the logistic regression model
summary(mod_test)

# Predicting the phytobenthos status class in case of highland small rivers using the logistic regression model
predict(mod_test, type="response")

# Aggregating the predicted values
aggregate(predict(mod_test, type = "response") ~ FB_osztály_bin, FUN = mean, data = na.omit(FB_123_short))

# Creating a contingency table for predicted values with a threshold of 0.5. 
# Error rate for the overall estimation can be calculated based on the contingency table.
table(as.numeric(predict(mod_test, type = "response") > 0.5), na.omit(FB_123_short)$FB_osztály_bin)




# Creating the type "Big rivers" in case of phytobenthos by subsetting the data and selecting the 5 most 
# important variables based on the previously made random forest model.
FB_478910_short <-  FB_data_big[FB_data_big$biol_tipus%in%c(4,7,8,9,10),(colnames(FB_data_big)%in%c(
  "FB_osztály", # phytobenthos status class
  "ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált.", # continuity status class
  "Mennyiség.Összes.lebegő.anyag", # suspended matter
  "Mennyiség.Foszfor..összes.", # total P
  "Mennyiség.Összes.szerves.szén..TOC.", # TOC
  "Mennyiség.Ortofoszfát"))] # orthophosphate

# Removing empty status classes (with no data)
FB_478910_short$FB_osztály <- factor(FB_478910_short$FB_osztály, levels=c("bad", "poor", "moderate","good", "high")[c("bad", "poor", "moderate","good", "high")%in%unique(FB_478910_short$FB_osztály)])

# Classifying status classes into two classes: good or better and moderate or worse
FB_478910_short$FB_osztály_bin <- NA
FB_478910_short$FB_osztály_bin[FB_478910_short$FB_osztály%in%c("poor","moderate")] <- 0
FB_478910_short$FB_osztály_bin[!(FB_478910_short$FB_osztály%in%c("poor","moderate"))] <- 1
FB_478910_short$FB_osztály_bin[is.na(FB_478910_short$FB_osztály)] <- NA

# table(FB_478910_short$FB_osztály_bin,FB_478910_short$FB_osztály)

# Performing logistic regression on the data of big rivers with the 5 chosen variables
mod_test <- glm(FB_osztály_bin~ÁLLAPOTÉRTÉKELÉS.ÁTJÁRHATÓSÁG..validált.+ # continuity status class
                  Mennyiség.Összes.lebegő.anyag+ # suspended matter
                  Mennyiség.Foszfor..összes.+ # total P
                  Mennyiség.Összes.szerves.szén..TOC.+ # TOC
                  Mennyiség.Ortofoszfát, # orthophosphate
                data=FB_478910_short,
                family=binomial)

# Printing the summary of the logistic regression model
summary(mod_test)

# Predicting the phytobenthos status class in case of big rivers using the logistic regression model
predict(mod_test, type="response")

# Aggregating the predicted values
aggregate(predict(mod_test, type="response")~FB_osztály_bin, FUN=mean, data=na.omit(FB_478910_short))

#Creating a contingency table for predicted values with a threshold of 0.5. 
# Error rate for the overall estimation can be calculated based on the contingency table.
table(as.numeric(predict(mod_test, type="response")>0.5),na.omit(FB_478910_short)$FB_osztály_bin)





# Creating the type "lowland small watercourses" in case of phytobenthos by subsetting the data and selecting the 5 most 
# important variables based on the previously made random forest model.
FB_56_short <-  FB_data[FB_data$biol_tipus%in%c(5,6),(colnames(FB_data)%in%c(
  "FB_osztály", # phytobenthos status class
  "Mennyiség.Nitrit.nitrogén..NO2.N.", # NO2-N
  "Mennyiség.Vezetőképesség", # electrical conductivity
  "Mennyiség.Klorid", # chloride
  "Mennyiség.Biokémiai.oxigénigény..BOI5.", # BOD5
  "Mennyiség.Ortofoszfát"))] # orthophosphate

# Removing empty status classes (with no data)
FB_56_short$FB_osztály <- factor(FB_56_short$FB_osztály, levels=c("bad", "poor", "moderate","good", "high")[c("bad", "poor", "moderate","good", "high")%in%unique(FB_56_short$FB_osztály)])

# Classifying status classes into two classes: good or better and moderate or worse
FB_56_short$FB_osztály_bin <- NA
FB_56_short$FB_osztály_bin[FB_56_short$FB_osztály%in%c("poor","moderate")] <- 0
FB_56_short$FB_osztály_bin[!(FB_56_short$FB_osztály%in%c("poor","moderate"))] <- 1
FB_56_short$FB_osztály_bin[is.na(FB_56_short$FB_osztály)] <- NA

#table(FB_56_short$FB_osztály_bin,FB_56_short$FB_osztály)

# Performing logistic regression on the data of lowland small watercourses with the 5 chosen variables
mod_test <- glm(FB_osztály_bin~Mennyiség.Vezetőképesség+ # electrical conductivity
                Mennyiség.Nitrit.nitrogén..NO2.N.+ # NO2-N
                Mennyiség.Biokémiai.oxigénigény..BOI5.+ # BOD5
                Mennyiség.Klorid+ # chloride
                Mennyiség.Ortofoszfát, # orthophosphate
                data=FB_56_short,
                family=binomial)

# Printing the summary of the logistic regression model
summary(mod_test)

# Predicting the phytobenthos status class in case of lowland small rivers using the logistic regression model
predict(mod_test, type="response")

# Aggregating the predicted values
aggregate(predict(mod_test, type="response")~FB_osztály_bin, FUN=mean, data=na.omit(FB_56_short))

# Creating a contingency table for predicted values with a threshold of 0.5. 
# Error rate for the overall estimation can be calculated based on the contingency table.
table(as.numeric(predict(mod_test, type="response")>0.5),na.omit(FB_56_short)$FB_osztály_bin)




########## FP ###########

# Creating the type "big rivers" in case of phytoplankton by subsetting the data and selecting the 5 most 
# important variables based on the previously made random forest model.
FP_478910_short <-  FP_data_big[FP_data_big$biol_tipus%in%c(4,7,8,9,10),(colnames(FP_data_big)%in%c(
  "FP_osztály", # phytoplankton status class
  "Mennyiség.Klorid", # chloride
  "Mennyiség.Ammónia.ammónium.nitrogén", # NH4-N
  "Mennyiség.Összes.nitrogén", # total N
  "Mennyiség.Biokémiai.oxigénigény..BOI5.", # BOD5
  "Mennyiség.KOIps..permanganátos.kémiai.oxigénigény..FEV." # COD Mn
  ))]

# Classifying status classes into two classes: good or better and moderate or worse
FP_478910_short$FP_osztály_bin <- NA
FP_478910_short$FP_osztály_bin[FP_478910_short$FP_osztály%in%c("bad","poor","moderate")] <- 0
FP_478910_short$FP_osztály_bin[!(FP_478910_short$FP_osztály%in%c("bad","poor","moderate"))] <- 1
FP_478910_short$FP_osztály_bin[is.na(FP_478910_short$FP_osztály)] <- NA

#table(FP_478910_short$FP_osztály_bin,FP_478910_short$FP_osztály)

# Performing logistic regression on the data of highland small watercourses with the 5 chosen variables
mod_test <- glm(FP_osztály_bin~Mennyiség.Biokémiai.oxigénigény..BOI5.+ # BOD5
                Mennyiség.Klorid+ # chloride
                Mennyiség.Ammónia.ammónium.nitrogén+ # NH4-N
                Mennyiség.Összes.nitrogén+ # total N
                Mennyiség.KOIps..permanganátos.kémiai.oxigénigény..FEV., # COD Mn
                data=FP_478910_short,
                family=binomial)

# Printing the summary of the logistic regression model
summary(mod_test)

# Predicting the phytoplanlton status class in case of highland small rivers using the logistic regression model
predict(mod_test, type="response")

# Aggregating the predicted values
aggregate(predict(mod_test, type="response")~FP_osztály_bin, FUN=mean, data=na.omit(FP_478910_short))

# Creating a contingency table for predicted values with a threshold of 0.5. 
# Error rate for the overall estimation can be calculated based on the contingency table.
table(as.numeric(predict(mod_test, type="response")>0.5),na.omit(FP_478910_short)$FP_osztály_bin)





########## MF ###########

# Creating the type "highland small rivers" in case of macrophytes by subsetting the data and selecting the 5 most 
# important variables based on the previously made random forest model.
MF_123_short <-  MF_data[MF_data$biol_tipus%in%c(1,2,3),(colnames(MF_data)%in%c(
  "MF_osztály", # macrophytes status class
  "nont_agrp", # proportion of extensive agricultural areas on the catchment
  "Vegyes.mezőgazdasági.terület.aránya.a.vízgyűjtőn....", # proportion of heterogeneous agricultural areas on the catchment
  "Mennyiség.Összes.lebegő.anyag", # suspended matter
  "MORFOLÓGIAI.ÁLLAPOT..validált.", # morphological status
  "intagrp" # proportion of intensive agricultural areas on the catchment
  ))]

# Classifying status classes into two classes: good or better and moderate or worse
MF_123_short$MF_osztály_bin <- NA
MF_123_short$MF_osztály_bin[MF_123_short$MF_osztály%in%c("bad","poor","moderate")] <- 0
MF_123_short$MF_osztály_bin[!(MF_123_short$MF_osztály%in%c("bad","poor","moderate"))] <- 1
MF_123_short$MF_osztály_bin[is.na(MF_123_short$MF_osztály)] <- NA

# table(MF_123_short$MF_osztály_bin,MF_123_short$MF_osztály)


# Performing logistic regression on the data of highland small watercourses with the 5 chosen variables
mod_test <- glm(MF_osztály_bin~Vegyes.mezőgazdasági.terület.aránya.a.vízgyűjtőn....+ # proportion of heterogeneous agricultural areas on the catchment
                  nont_agrp+  # proportion of extensive agricultural areas on the catchment
                  Mennyiség.Összes.lebegő.anyag+
                  MORFOLÓGIAI.ÁLLAPOT..validált.+
                  intagrp,
                data=MF_123_short,
                family=binomial)

# Printing the summary of the logistic regression model
summary(mod_test)

# Predicting the macrophytes status class in case of highland small rivers using the logistic regression model
predict(mod_test, type="response")

# Aggregating the predicted values
aggregate(predict(mod_test, type="response")~MF_osztály_bin, FUN=mean, data=na.omit(MF_123_short))

# Creating a contingency table for predicted values with a threshold of 0.5. 
# Error rate for the overall estimation can be calculated based on the contingency table.
table(as.numeric(predict(mod_test, type="response")>0.5),na.omit(MF_123_short)$MF_osztály_bin)




# Creating the type "lowland small rivers" in case of macrophytes by subsetting the data and selecting the 5 most 
# important variables based on the previously made random forest model.
MF_56_short <-  MF_data[MF_data$biol_tipus%in%c(5,6),(colnames(MF_data)%in%c(
  "MF_osztály", # macrophytes status class
  "Mennyiség.KOIps..permanganátos.kémiai.oxigénigény..FEV.", # COD Mn
  "Mennyiség.Összes.szerves.szén..TOC.", # TOC
  "Mennyiség.Ortofoszfát",  # orthophosphate
  "Mennyiség.Vezetőképesség", # electrical conductivity
  "Mennyiség.Klorid" # chloride
  ))]

# Classifying status classes into two classes: good or better and moderate or worse
MF_56_short$MF_osztály_bin <- NA
MF_56_short$MF_osztály_bin[MF_56_short$MF_osztály%in%c("bad","poor","moderate")] <- 0
MF_56_short$MF_osztály_bin[!(MF_56_short$MF_osztály%in%c("bad","poor","moderate"))] <- 1
MF_56_short$MF_osztály_bin[is.na(MF_56_short$MF_osztály)] <- NA

# table(MF_56_short$MF_osztály_bin,MF_56_short$MF_osztály)

# Performing logistic regression on the data of lowland small watercourses with the 5 chosen variables
mod_test <- glm(MF_osztály_bin~Mennyiség.KOIps..permanganátos.kémiai.oxigénigény..FEV.+ # COD Mn
                  Mennyiség.Összes.szerves.szén..TOC.+ # TOC
                  Mennyiség.Ortofoszfát+  # orthophosphate
                  Mennyiség.Vezetőképesség+ # electrical conductivity
                  Mennyiség.Klorid, # chloride
                data=MF_56_short,
                family=binomial)

# Printing the summary of the logistic regression model
summary(mod_test)

# Predicting the macrophytes status class in case of lowland small rivers using the logistic regression model
predict(mod_test, type="response")

# Aggregating the predicted values
aggregate(predict(mod_test, type="response")~MF_osztály_bin, FUN=mean, data=na.omit(MF_56_short))

# Creating a contingency table for predicted values with a threshold of 0.5. 
# Error rate for the overall estimation can be calculated based on the contingency table.
table(as.numeric(predict(mod_test, type="response")>0.5),na.omit(MF_56_short)$MF_osztály_bin)


