# -*- coding: utf-8 -*-
"""102003466.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1MIh7z9ZI-L8cfmGQ57_aBYR5smGKBTrY

**Writing the data of excel file into csv file**
"""

import pandas as pd

# Read and store content
# of an excel file
read_file = pd.read_excel ("102003466-data.xlsx")

# Write the dataframe object
# into csv file
#here we are using the to_csv to convert excel to csv 
read_file.to_csv ("102003466-data.csv",
				index = None,
				header=True)
	
# read csv file and convert
# into a dataframe object
df = pd.DataFrame(pd.read_csv("102003466-data.csv"))

# show the dataframe

dataframe1=df.copy()

"""**Step 1: To convert the categorical data to numerical data**

Since there is no categorical data so there is no need of that

**Step 2: Vector Normalization**
"""

def vector_normalize(dataset,ncol):

  for i in range(1,ncol):
    y=0
    for j in range(len(dataset)):
      y = y + df.iloc[j, i]**2
    y = y**0.5
    for j in range(len(df)):
      dataset.iat[j, i] = (dataset.iloc[j, i] / y)
  print(dataset)
  return dataset

"""**Step 3:Weight Assignment**"""

def weight(df,ncol,weights):
  for i in range(1,ncol):
    for j in range(len(df)):
      df.iat[j,i]=df.iloc[j,i]*weights[i-1]
  return df

"""**Step 4:Finding ideal best and ideal worst**"""

def Calc_ideal_Values(df, nCol, impact):
    #calculating ideal best and ideal worst
    ideal_positive_value = (df.max().values)[1:] #positive value i.e if impact is + then maximum will be our ideal positive value 
    ideal_negative_value = (df.min().values)[1:] #negative value i.e if impact is + then minimum will be our ideal negative value
    #now we need to check when our impact is negative
    #now we will run our loop from 1 to last column and check if our impact is negative or not if it is then we need to interchange the ideal postive and ideal negative 

    for i in range(1, nCol):
        if impact[i-1] == '-':
            ideal_positive_value[i-1], ideal_negative_value[i-1] = ideal_negative_value[i-1], ideal_positive_value[i-1]
    return ideal_positive_value, ideal_negative_value

"""**Step 5:Calculate Euclidean Distance ,score and Rank**"""

import math
def euclidean_distance(dataset,ncol,weights,impact,df1):

  #first of all normalize the vector 
  dataset=vector_normalize(dataset,ncol)
  

  #second:weight assignment 
  dataset1=weight(dataset,ncol,weights)
  

  #ideal postive and ideal negtaive values calculation
  ideal_p,ideal_n=Calc_ideal_Values(dataset1,ncol,impact)
  

 #calculating the euclidean distance 
  perf_score=[]
  for i in range(len(dataset1)):
    s_positive,s_negative=0.0 , 0.0
    for j in range(1,ncol):
      
      s_positive=s_positive+(ideal_p[j-1]-dataset1.iloc[i,j])**2
      s_negative=s_negative+(ideal_n[j-1]-dataset1.iloc[i,j])**2
  
    s_positive=math.sqrt(s_positive)
    s_negative=math.sqrt(s_negative)
    
   

    perf_score.append(s_negative/(s_negative+s_positive))
    # print(perf_score)
    #Score 
  df1['Topsis Score']=perf_score
  # #Rank 
  df1['Rank'] = (df1['Topsis Score'].rank(method='max', ascending=False))
  df1 = df1.astype({"Rank": int})

  df1.to_csv('102003466-result.csv',index=False)
  print(df1)
  return df1

import sys
import os
def main():
  if(len(sys.argv))!=5:
    print('ERROR: Enter the correct number of parameters')
    print("Enter like this:python 102003466.py 102003466-data.csv '1,1,0,1,0' '+,-,+,-,+' 102003466-result.csv")
    exit(1)

  elif not os.path.isfile(sys.argv[1]):
        print(f"ERROR : {sys.argv[1]} Don't exist!!")
        exit(1)

  elif ".csv" != (os.path.splitext(sys.argv[1]))[1]:
        print(f"ERROR : {sys.argv[1]} is not csv!!")
        exit(1)
  else:
    data=pd.read_csv(sys.argv[1])
    data1=pd.read_csv(sys.argv[1])
    if(len(data1.columns)<3):
      print('ERROR: File contains less than 3 columns, Please enter the correct number of columns to proceed further')
    
    for i in range(1,len(data1.columns)):
      pd.to_numeric(data.iloc[:,i],errors='coerce')
      data.iloc[:, i].fillna((data.iloc[:, i].mean()), inplace=True)

    try:
      weights = [int(i) for i in sys.argv[2].split(',')]
    except:
      print('ERROR:error is in weights array')

    impact=sys.argv[3].split(',')
    for i in impact:
      if not (i =='+' or i=='-'):
        print('ERROR:It is in impact array')

    if(len(data.columns)) !=len(weights)+1 or len(data.columns)!=len(impact)+1:
      print('ERROR occured')
      print('Number of columns and number of weights,impact are not same so please enter the correct number of columns for the same !!!')
      exit(1)

    if (".csv" != (os.path.splitext(sys.argv[4]))[1]):
      print("ERROR : Output file extension is wrong")
      exit(1)
    if os.path.isfile(sys.argv[4]):
      os.remove(sys.argv[4])
        # print(" No error found\n\n Applying Topsis Algorithm...\n")
    euclidean_distance(data1,len(data1.columns),weights,impact,data)

if __name__ == "__main__":
    main()