cat("\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n")
# Programmer : Mohammad Lakhi
# Student ID : 2512430
# Module     : ACCA7022-	Advanced Statistical Programming
#File Title  : Data Manipulation Assignment 
# Purpose    : Managing an alien colony on a distant planet resources production data across
#              30 Sols, 6 Stations and 4 Teams. Perform aggregation, anomaly detection,
#              peak production analysis and efficiency  score using loops.
# Month      : February,2026

cat("\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n")

#This make sure that we get same random numbers when we run the code
set.seed(42)

#Storing key values as constant
no_sol     <- 30 #number of days in the simulation
no_station <- 6  #number of station in the colony
no_teams   <- 4  #number of Workers team per station
base_output<- 50 #Daily production output for the team

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Task A :Generate Production Data 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Using three nested loops to fill 720 rows of data
#First loop : goes through each day (1-30)
#Second loop : goes through each station(1-6)
#Third loop : goes through each team(1-4)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Create a table with 720 rows(30x6x4=720)
total_rows <- no_sol * no_station * no_teams

#Creating 4 empty columns to be filled
col_sol <- integer(total_rows)    #storing the day numbers
col_station <- integer(total_rows)#storing the station numbers
col_teams <- integer(total_rows)  #storing the team numbers
col_output <- numeric(total_rows) #storing the output values


row_index <- 1



#First loop : goes through each day
for (sol in 1:no_sol) {
  
  #Second loop : goes through each station
  for (station in 1:no_station) {
    
    #Third loop : goes through each team
     for (team in 1:no_teams){
      
      #RANDOM NOISE(picks a number between -5:5)
      r_noise <- sample(-5:5, size = 1)
      
      
      #OUTPUT FORMULA
      #Calculates the output for the day,station and team
      output_value <- base_output + (station*3) + (team*2) + r_noise
      
      
      #Stores values in the specific columns
      col_sol[row_index] <- sol
      col_station[row_index] <- station
      col_teams[row_index] <- team
      col_output[row_index] <- output_value
      
      #It moves to the next row
      row_index <- row_index +1
      
      
    }
  }
}


#Combining all four columns into one table
production_data <- data.frame(
  sol =col_sol,
  station = col_station,
  team = col_teams,
  output = col_output
)

cat("~~~Task-A: First 10 rows of Production Data~~~ \n")
print(production_data[1:10, ])



#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Task B :Total Production per Station
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#For each station we go through all 720 rows  and sum up all outputs that belongs to that station
#We have use a running total variable that starts at zero for each station 
#It keeps up adding until it goes through each row
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Creating two empty columns for station and total  
station_id <- integer(no_station)
station_vectors <- numeric(no_station)

#looping through each station and summing up all outputs
for (station in 1:no_station) {
  
  
  station_id[station] <- station #Saves the station number 
  
  running_total <- 0
  
  #Loop to go through every single row in production_data
  for (row in 1:nrow(production_data)) {
    
    if (production_data$station[row] == station){
      running_total <-running_total+production_data$output[row]
    }
  }
  
  #Saves the final total for the specific station 
  station_vectors[station] <- running_total
  
}


#build a table for results 
station_totals <- data.frame(
  station = station_id,
  totaloutput = station_vectors
)


#results
cat("\n ~~~ Task-B: Station Totals ~~~ \n")
print(station_totals)



#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Task-C: Detect Production Anomalies 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#for each day  and each station we have done three  steps:
#Step 1 : Add up all 4 teams output to get daily total 
#Step 2 : Divide by 4  to get daily average
#Step 3 : Check each teams output against the average
#-> If it is more 10 percent it is marked TRUE
#-> If its below 10 percent it is marked FALSE
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Creating 5 empty columns for anomaly 
anomaly_sol <- integer(total_rows)
anomaly_station <- integer(total_rows)
anomaly_team <- integer(total_rows)
anomaly_output<- integer(total_rows)
anomaly <- logical(total_rows)

#resetting row index to 1 for filling it with anomalies
row_index <- 1

#Loop to go through each day
for (sol in 1:no_sol) {
  
  #Loop to go through each station
  for (station in 1:no_station) {
    
    
    #	Calculate the daily total output 
    daily_total <- 0 
    for (row in 1:nrow(production_data)) {
      if (production_data$sol[row] == sol &&
        production_data$station[row] == station) {
          daily_total <- daily_total + production_data$output[row]
        }
    }
    
    #Calculate the daily average by dividing total output/no. of teams 
    daily_average <- daily_total/ no_teams
    
    #Comparison of each teams output beside daily avg
    for (row in 1:nrow(production_data)) {
      if (production_data$sol[row]== sol &&
          production_data$station[row]== station){
        team_op <- production_data$output[row]
        
        #calculation of deviation percentage
        deviation <- abs(team_op - daily_average)/daily_average*100
        
        #Stores TRUE if deviation is more than 10% otherwise FALSE
        anomaly[row_index]<- deviation>10
        
        #Saves all values at the current position
        anomaly_sol[row_index]<-sol
        anomaly_station[row_index]<-station
        anomaly_team[row_index]<-production_data$team[row]
        anomaly_output[row_index]<-team_op
        
        #Moves to next row
        row_index <- row_index +1
      }
      
    }
  }
  
}

#Anomalies table for five vectors
anomalies<- data.frame(
  sol = anomaly_sol,
  station = anomaly_station,
  team = anomaly_team,
  output = anomaly_output,
  Anomaly= anomaly
)

#Prints only first 10 anomalies (which are true)
cat("\n~~~ Task C: First 10 Anomalies \n")
an_count<- 0
for (row in 1:nrow(anomalies)) {
  if (anomalies$Anomaly[row] == TRUE){
    print(anomalies[row, ])
    an_count<- an_count+1
    
    #stops at 10
    if(an_count == 10 ) break
  }
  
}




#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Task D : Identify Peak Productivity Days 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#We have gone through 30 days for each station
#Add up all team output for that day
#Tracked the highest total value using vector best_op 
#best_op start at the lowest possible value (-Inf)
#Every time it finds a  higher total value, best_op and best_sol is updated
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#3 empty tables for the results
peak_station<- integer(no_station) #station number 
peak_sol <- integer(no_station)    #day with the highest output
peak_op <- numeric(no_station)     #highest total output value


#Loop to go through each station
for (station in 1:no_station) {
  
  best_sol <- -1
  best_op  <- -Inf #lowest possible output value
  
  
  #Loop to go through each day
  for (sol in 1:no_sol) {
    
    #starts total at 0 for this day
    sol_total <- 0
    
    for (row in 1:nrow(production_data)) {
      if (production_data$station[row]== station &&
          production_data$sol[row] == sol) {
        sol_total<- sol_total + production_data$output[row]
      }
      
    }
    
    
    #Comparision of sol_total with the best current best value
    if (sol_total > best_op) {
      best_op<- sol_total
      best_sol <- sol
    }
    
  }
  
  # after checking all solutions, storing the peak solution values
  peak_station[station] <- station
  peak_sol[station] <- best_sol
  peak_op[station]<- best_op
  
}


#Building peak days Data frame

peak_days <- data.frame(
  station = peak_station,
  sol = peak_sol,
  total_output =peak_op
  
)

#Print peak days resukt
cat("\n~~~ Task D: Peak Productivity Days per Station ~~~\n")
print(peak_days)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Task E : Calculate Efficiency Score 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Adding a new column called efficiency_score to production_data
#Higher value means it have produce output relative to their station and team number combined
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#new column for efficiency score
production_data$efficiency_score <- numeric(nrow(production_data))

#looping through every row and calculate efficiency score

for (row in 1:nrow(production_data)) {
  
  #FORMULA
  production_data$efficiency_score[row]<- production_data$output[row]/(production_data$station[row]+production_data$team[row])
  
}

#Printing first 10 rows of the updated dataframe

cat("\n~~~ Task E : First 10 Rows with efficinecy score   ~~~\n")
print(production_data[1:10, ])
