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

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1yDVYrFus6ZBZyd8a8QRIqCkBzTwgCa9l
"""

import pandas as pd
import numpy as np
import math
import sys
import os
def main():
  topsis_score(csv,weightss,impactss,resultname)

def topsis_score(csv,weightss,impactss,resultname):
    # n=len(sys.argv)
    # if n!=5:
    #   raise Exception("Wrong number of args.") #No. of arguments
    # try:
    #   f = open(sys.argv[1], 'r')
    # except FileNotFoundError:
    #   raise Exception("Input File not found") # file not found
    # name, extension = os.path.splitext(sys.argv[1])
    # if extension!='.csv':
    #   raise Exception("Input file is not a csv file") #not a csv file
    # name2, extension2 = os.path.splitext(sys.argv[4])
    # if extension2!='.csv':
    #   raise Exception("Output file is not a csv file")

    df=pd.read_csv(csv)

    df=df.drop(df.columns[[0]], axis=1)
    df

    total_cols=len(df.axes[1])
    total_rows=len(df.axes[0])


    # print(df.iloc[0,0])

    for i in range(0,total_cols):
      sum=0
      for j in range(0,total_rows):
        sum+=df.iloc[j,i]**2
      for k in range(0,total_rows):
        df.iloc[k,i]/=math.sqrt(sum)

    weights=weightss
    li=weights.split(",")
    flag=0
    for i in range(len(li)):
      if li[i].isdigit():
        li[i]=int(li[i])
      elif li[i].replace('.','',1).isdigit() and li[i].count('.') < 2:
        li[i]=float(li[i])
      else:
        flag=1
    if flag==1:
      raise Exception("Weights must be ',' separated")
    for i in range(0,total_cols):
      df.iloc[:,i]*=li[i]

    vjpluslist = []
    # x=math.ceil(len(sys.argv[2])/2)
    for i in range(len(li)):
       vjpluslist.append(i)

    vjminuslist = []
    for i in range(len(li)):
       vjminuslist.append(i)

    impacts=impactss
    imp=[]
    f=0
    for i in range(len(impacts)):
        if(i%2==0):
          if(impacts[i]=='+' or impacts[i]=='-'):
            imp.append(impacts[i])
          else:
            f=1
    if f==1:
      raise Exception("Impacts should either be '+' or '-'") # + or - weights

    fl=0
    for i in range(len(impacts)):
      if(i%2!=0):
        if impacts[i]!=',':
          fl=1
    if fl==1:
      raise Exception("Impacts must be ',' separated") #impacts ',' separated
    df1=df.applymap(np.isreal)
    ro=df1.shape[0]
    co=df1.shape[1]
    fla=0
    for i in range(1,co):
      if df1.iloc[0,i]==False:
        fla=1
    if fla==1:
      raise Exception("Second to last column must be numeric") #second to last column numeric
    c=pd.read_csv(csv).shape[1]
    if c<3:
      raise Exception("Number of Columns in the input file are less than 3.") # no. of input files
    if len(imp)==len(li) and len(li)==c-1:
      pass
    else:
      raise Exception("No. of weights, impacts and No. of numerical rows must be equal") # no. of weights, impacts and columns  
    for  i in range(0,total_cols):
      vjplus=0
      vjminus=0
      if impacts[i*2] == '+':
        vjpluslist[i]=df.iloc[:,i].max()
        vjminuslist[i]=df.iloc[:,i].min()
      else: 
        vjpluslist[i]=df.iloc[:,i].min()
        vjminuslist[i]=df.iloc[:,i].max()    
    df.loc[len(df)] = vjpluslist
    df.loc[len(df)] = vjminuslist


    sjpluslist=[]
    for i in range(len(df.iloc[:,0])):
       sjpluslist.append(i)

    sjminuslist=[]
    for i in range(len(df.iloc[:,0])):
       sjminuslist.append(i)

    for i in range(0,total_rows):
      sumplus=0
      summinus=0
      for j in range(0,total_cols):
        sumplus+=(vjpluslist[j]-df.iloc[i,j])**2
        summinus+=(vjminuslist[j]-df.iloc[i,j])**2
      sjpluslist[i]=math.sqrt(sumplus)
      sjminuslist[i]=math.sqrt(summinus)
    # print(sjpluslist)
    # print(sjminuslist)

    df['sj+'] = np.array(sjpluslist)
    df['sj-'] = np.array(sjminuslist)


    sum_column = df["sj+"] + df["sj-"]
    df["S+_+_S-"] = sum_column


    update_df = df.drop([df.index[-1], df.index[-2]])


    performance=[]
    for i in range(len(df.iloc[:,0])-2):
      performance.append(i)
    for i in range(len(df.iloc[:,0])-2):
      for j in range(len(df.iloc[:,0])-2):
         performance[i]=update_df.iloc[i,-2]/update_df.iloc[i,-1]
    # print(performance)

    update_df['Performance_score'] = np.array(performance)


    topsis_score=pd.DataFrame()

    topsis_score['Fund_Name']=pd.read_csv(csv).iloc[:,0]
    topsis_score['Performance_Score']=update_df.iloc[:,-1]
    topsis_score["Rank"] = update_df["Performance_score"].rank(ascending=0)

    result=pd.read_csv(csv)
    result['Topsis_Score']=topsis_score.iloc[:,-2]
    result['Rank']=topsis_score.iloc[:,-1]
    result.to_csv(resultname)
if __name__ == '__main__':
    main()