# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .r
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: R
#     language: R
#     name: ir
# ---

# # Assumptions of Linear Regression

# Data Source should be evaluted in accordane with multicolinearity, equal variance, autocorrelation and so on. Linear Regression is only half to build up something. The important point is how our data comply with our regression model.

# # Assumption 1

# + active=""
# Libraries
# -

if(!require(readxl)) {
  install.packages("readxl"); require(readxl)
}
if(!require(lmtest)){
  install.packages("lmtest"); require(lmtest)
}
if(!require(corrplot)) {
  install.packages("corrplot"); require(corrplot)
}
if(!require(car)) {
  install.packages("car"); require(car)
}
if(!require(gvlma)) {
  install.packages("gvlma"); require(gvlma)  
}


# + active=""
# The mean of residuals is zero. Check the mean of residuals! 
# -

#The following line provides you a GUI screen which helps to select your file.
#my_data <- read_excel(file.choose())
currentDirectory <- getwd()
setwd("C:\\Users\\zoint\\Desktop\\AllFiles\\Projeler\\R_Projects")
directoryChanged <- getwd()
my_data <- read_excel("Autoform_1000.xlsx")

meanResidual <- function(){
  mod <- lm(HARDNESSP1 ~ TransportTimeAfterHeating, data = my_data)
  mean (mod$residuals)
}
meanResidual()

# # Assumption 2

# + active=""
# Homoscedasity of residuals or equal variance 
# -

homosCedasticity <- function(){
  par(mfrow = c(2,2)) # set 2 rows and 2 column  plot layout
  mod_layout <- lm(HARDNESSP1 ~ TransportTimeAfterHeating, data = my_data)
  plot(mod_layout)
}
homosCedasticity()


# ![test%20picture.png](attachment:test%20picture.png)

# # Autocorrelation (Assumption 3)

# + active=""
# Autocorrelation normally applies on time series data. Because time series data plot correlated each other and this would helpful for the machine learning applications. When the residuals (error) are autocorrelated, it means that the current value is dependent of the previous (historic) values and there is a definite unexplained pattern in the Y variable that shows up in the disturbances.
# -

autocorrelation <- function()
{
  lmMod <- lm(thickness ~ spacing, data = my_data)
  acf(lmMod$residuals)
  #Durbin - <NAME>
  #If the result is higher than 0, then our data is autocorrelated.
  print(lmtest::dwtest(lmMod))
}
autocorrelation()

# + active=""
# If you check the plot out, you will not see a single line under the dashed (blue) region. This shows us that the data model abide by the autocorrelation rules.
# -

# # Assumption 4

# + active=""
# The variability in X values is positive. So how to check?
# -

variabilityInX <- function(){
  if(var(my_data$thickness) > 0.0 && var(my_data$TransportTimeAfterHeating) > 0.0
     && var(my_data$EnforcedTemperatureOfEntireSheet) > 0.0 && var(my_data$QuenchingTimeInTool) > 0.0 &&
     var(my_data$QuenchingForce) > 0.0 && var(my_data$spacing) > 0.0 && var(my_data$DefaultToolTemperature) > 0.0)
  {
    print("Variability checked")
  } else
  {
    print("Variability is not checked")
  } 
}
variabilityInX()

# # Assumption 5

# + active=""
# There is no perfect relationship between independent Variables. Check Variance Inflation Factor(VIF)
# -

# ![A%20Formula.JPG](attachment:A%20Formula.JPG)

mod2 <- lm(HARDNESSP1 ~ ., data=my_data[1:9])
vif(mod2)


# + active=""
# Check correlation plot
# -

apply(my_data, 2, function(x) sum(is.na(x)))
corrplot(cor(my_data))

# # Check Assumption Automatically

# + active=""
# The gvlma() function check the important assumptions on a given linear model
# -

par(mfrow=c(2,2)) 
gvlmaMod <- lm(thickness ~ spacing, data = my_data[1:8, ])
gvlma::gvlma(gvlmaMod)

# + active=""
# Explanation of the variable of gvlma()

# + active=""
# Global Stat: Are the relationships between your X (independent variables) and Y (dependent variable)roughly linear? Rejection of the null (p < 0.5) indicates a non-linear relationship between the variables.
#
# Skewness: Is your distribution turn positively or negatively, necessitating a transformation to meet the assumption of normality? If the skewness couldn't reach p < 0.5, then you should transform your data.
#
# Kurtosis: Is your data highly peaked or shallowly peaked, necessitating a transformation to meet the assumption of normality?
#
# Link Function: Is your dependent variable truly continuous, or categorical? Rejection of null (p < 0.5) indicates that you should utilize a different linear model (e.g. logistic regression)
#
# Heteroscedasticity: Is the variance of your model residuals constant across the range of X? That shows your model whether it is better or worse at predicting for certain range of your X scales.
# -

# # Historical Data Fault Diagnosis System

# + active=""
# A new fault Diagnosis Method using Fault Directions in Fisher Discriminant Analysis

# + active=""
# Following three methods will be implemented

# + active=""
# 1) Principal Component Analysis (PCA)
# 2) Partial Least Square (PLS)
# 3) Statistical Process Monitoring (SPM) in Fault Detection

# + active=""
# In Historical Data Fault Diagnosis System one can carry out the system within three stages.
# 1) Data preanalysis
# 2) Fault Visualization
# 3) Fault Diagnosis

# + active=""
# Process monitoring method is composed of three parts

# + active=""
# 1) A Preanalysis step that first roughly ioutput dentifies various clusters in a historical output data set -> isolate normal and abnormal data clusters by the k-means clustering method.
# 2) A fault visualization step that visualise high-dimensional data in 2-D space by performing global Fisher Discriminant Anaylsis (FDA)
# 3) A new fault diagnosis method based on fault directions in pairwise FDA.
#
# Subsections:
# 1) Preliminary
# 2) PCA-based process monitoring 
# 3) Fisher Discriminant Analysis
# 4) K-Means Clustering

# +
if(!require(readxl)) {
  install.packages("readxl"); require(readxl)
}
if(!require(MASS)) {
  install.packages("MASS"); require(MASS)
}
if(!require(factoextra)) {
  install.packages("factoextra"); require(factoextra)
}


currentDirectory <- getwd()
setwd("C:\\Users\\zoint\\Desktop\\AllFiles\\Projeler\\R_Projects")
directoryChanged <- getwd()
#print out new directory address
print(directoryChanged)

my_data <- read_excel("Autoform_1000.xlsx")
#Normalization
NaValue <- function (x) { sum(is.na(x))}
apply(my_data, 2, NaValue)
#Principal component Analysis Part
my_data.principal <- my_data[1:999, 1:9]
print(head(my_data.principal[,1:9]))
pca.graph <- prcomp(my_data.principal, scale=TRUE)
#Visualisierung
# fviz_pca_biplot(pca.graph, repel = TRUE,
#                 col.var = "#2E9FDF", # Variables color
#                 col.ind = "#696969"  # Individuals color
# )

resultPlot <- fviz_pca_var(pca.graph, col.var="contrib")+
  scale_color_gradient2(low="orange", mid="blue",
                        high="red", midpoint=96) +
  theme_minimal()
print(resultPlot)

# Gradient color
resultHeatMap <- fviz_pca_ind(pca.graph, col.ind="cos2") +
  scale_color_gradient2(low="yellow", mid="blue",
                        high="red", midpoint=0.6)

print(resultHeatMap)

eigen.values <- get_eigenvalue(pca.graph)
print(eigen.values)

result.values <- get_pca_var(pca.graph)
result.values$coord
result.values$contrib
result.values$cos2

# Graph of individuals
# An alias of fviz_pca_biplot()
#Linear Discriminant Analysis
#It is a well-established machine learning techique for predicting categories. Its main advantages,
#compared to other classification algorithms such as neural networks and random forests, are that
#the model is interpretable and that prediction is easy
my_data.lda <- lda(HARDNESSP1 ~ ., data = my_data[1:9])
my_data.lda.values <- predict(my_data.lda)
# -





StarcoderdataJupyterScriptsDedupFiltered