<reponame>Samarth-Gupta-2909/Topsis_Samarth_102083050
import pandas as pd
import os
import sys

def main():
    # Arguments not equal to 5
    if len(sys.argv) != 5:
        print("ERROR : NUMBER OF PARAMETERS")
        print("USAGE : python topsis.py inputfile.csv '1,1,1,1' '+,+,-,+' result.csv ")
        exit(1)

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

    # File extension not csv
    elif ".csv" != (os.path.splitext(sys.argv[1]))[1]:
        print(f"ERROR : {sys.argv[1]} is not csv!!")
        exit(1)

    else:
        dataset, tem_dataset = pd.read_csv(sys.argv[1]), pd.read_csv(sys.argv[1])
        nCol = len(tem_dataset.columns.values)

        # less then 3 columns in input dataset
        if nCol < 3:
            print("ERROR : Input file have less then 3 columns")
            exit(1)

        # Handeling non-numeric value
        for i in range(1, nCol):
            pd.to_numeric(dataset.iloc[:, i], errors='coerce')
            dataset.iloc[:, i].fillna((dataset.iloc[:, i].mean()), inplace=True)

        # Handling errors of weighted and impact arrays
        try:
            weights = [int(i) for i in sys.argv[2].split(',')]
        except:
            print("ERROR : In weights array please check again")
            exit(1)

        impact = sys.argv[3].split(',')
        for i in impact:
            if not (i == '+' or i == '-'):
                print("ERROR : In impact array please check again")
                exit(1)

        # Checking number of column,weights and impacts is same or not
        if nCol != len(weights)+1 or nCol != len(impact)+1:
            print(
                "ERROR : Number of weights, number of impacts and number of columns not 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")
        topsis_samarth(tem_dataset, dataset, nCol, weights, impact)


def Normalisation(tem_dataset, nCol, weights):
    # normalizing the array
    # print(" Normalizing the DataSet...\n")
    for i in range(1, nCol):
        tem = 0
        for j in range(len(tem_dataset)):
            tem = tem + tem_dataset.iloc[j, i]**2
        tem = tem**0.5
        for j in range(len(tem_dataset)):
            tem_dataset.iat[j, i] = (tem_dataset.iloc[j, i] / tem)*weights[i-1]
    return tem_dataset


def Calculation(tem_dataset, nCol, impact):
    # print(" Calculating Positive and Negative values...\n")
    p_sln = (tem_dataset.max().values)[1:]
    n_sln = (tem_dataset.min().values)[1:]
    for i in range(1, nCol):
        if impact[i-1] == '-':
            p_sln[i-1], n_sln[i-1] = n_sln[i-1], p_sln[i-1]
    return p_sln, n_sln


def topsis_samarth(tem_dataset, dataset, nCol, weights, impact):
    # normalizing the array
    tem_dataset = Normalisation(tem_dataset, nCol, weights)

    # Calculating positive and negative values
    p_sln, n_sln = Calculation(tem_dataset, nCol, impact)

    # calculating topsis score
    #Generating Score And Rank
    score = []
    for i in range(len(tem_dataset)):
        tem_p, tem_n = 0, 0
        for j in range(1, nCol):
            tem_p = tem_p + (p_sln[j-1] - tem_dataset.iloc[i, j])**2
            tem_n = tem_n + (n_sln[j-1] - tem_dataset.iloc[i, j])**2
        tem_p, tem_n = tem_p**0.5, tem_n**0.5
        score.append(tem_n/(tem_p + tem_n))
    dataset['Topsis Score'] = score

    # calculating the rank according to topsis score
    dataset['Rank'] = (dataset['Topsis Score'].rank(method='max', ascending=False))
    dataset = dataset.astype({"Rank": int})

    # Writing the csv
    # print(" Writing Result to CSV...\n")
    dataset.to_csv(sys.argv[4], index=False)
    # print(" Successfully Terminated")


if __name__ == "__main__":
    main()
import pandas as pd
import os
import sys

def main():
    # Arguments not equal to 5
    if len(sys.argv) != 5:
        print("ERROR : NUMBER OF PARAMETERS")
        print("USAGE : python topsis.py inputfile.csv '1,1,1,1' '+,+,-,+' result.csv ")
        exit(1)

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

    # File extension not csv
    elif ".csv" != (os.path.splitext(sys.argv[1]))[1]:
        print(f"ERROR : {sys.argv[1]} is not csv!!")
        exit(1)

    else:
        dataset, tem_dataset = pd.read_csv(sys.argv[1]), pd.read_csv(sys.argv[1])
        nCol = len(tem_dataset.columns.values)

        # less then 3 columns in input dataset
        if nCol < 3:
            print("ERROR : Input file have less then 3 columns")
            exit(1)

        # Handeling non-numeric value
        for i in range(1, nCol):
            pd.to_numeric(dataset.iloc[:, i], errors='coerce')
            dataset.iloc[:, i].fillna((dataset.iloc[:, i].mean()), inplace=True)

        # Handling errors of weighted and impact arrays
        try:
            weights = [int(i) for i in sys.argv[2].split(',')]
        except:
            print("ERROR : In weights array please check again")
            exit(1)

        impact = sys.argv[3].split(',')
        for i in impact:
            if not (i == '+' or i == '-'):
                print("ERROR : In impact array please check again")
                exit(1)

        # Checking number of column,weights and impacts is same or not
        if nCol != len(weights)+1 or nCol != len(impact)+1:
            print(
                "ERROR : Number of weights, number of impacts and number of columns not 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")
        topsis_samarth(tem_dataset, dataset, nCol, weights, impact)


def Normalisation(tem_dataset, nCol, weights):
    # normalizing the array
    # print(" Normalizing the DataSet...\n")
    for i in range(1, nCol):
        tem = 0
        for j in range(len(tem_dataset)):
            tem = tem + tem_dataset.iloc[j, i]**2
        tem = tem**0.5
        for j in range(len(tem_dataset)):
            tem_dataset.iat[j, i] = (tem_dataset.iloc[j, i] / tem)*weights[i-1]
    return tem_dataset


def Calculation(tem_dataset, nCol, impact):
    # print(" Calculating Positive and Negative values...\n")
    p_sln = (tem_dataset.max().values)[1:]
    n_sln = (tem_dataset.min().values)[1:]
    for i in range(1, nCol):
        if impact[i-1] == '-':
            p_sln[i-1], n_sln[i-1] = n_sln[i-1], p_sln[i-1]
    return p_sln, n_sln


def topsis_samarth(tem_dataset, dataset, nCol, weights, impact):
    # normalizing the array
    tem_dataset = Normalisation(tem_dataset, nCol, weights)

    # Calculating positive and negative values
    p_sln, n_sln = Calculation(tem_dataset, nCol, impact)

    # calculating topsis score
    #Generating Score And Rank
    score = []
    for i in range(len(tem_dataset)):
        tem_p, tem_n = 0, 0
        for j in range(1, nCol):
            tem_p = tem_p + (p_sln[j-1] - tem_dataset.iloc[i, j])**2
            tem_n = tem_n + (n_sln[j-1] - tem_dataset.iloc[i, j])**2
        tem_p, tem_n = tem_p**0.5, tem_n**0.5
        score.append(tem_n/(tem_p + tem_n))
    dataset['Topsis Score'] = score

    # calculating the rank according to topsis score
    dataset['Rank'] = (dataset['Topsis Score'].rank(method='max', ascending=False))
    dataset = dataset.astype({"Rank": int})

    # Writing the csv
    # print(" Writing Result to CSV...\n")
    dataset.to_csv(sys.argv[4], index=False)
    # print(" Successfully Terminated")


if __name__ == "__main__":
    main()
# Arguments not equal to 5 # File Not Found error # File extension not csv # less then 3 columns in input dataset # Handeling non-numeric value # Handling errors of weighted and impact arrays # Checking number of column,weights and impacts is same or not # print(" No error found\n\n Applying Topsis Algorithm...\n") # normalizing the array # print(" Normalizing the DataSet...\n") # print(" Calculating Positive and Negative values...\n") # normalizing the array # Calculating positive and negative values # calculating topsis score #Generating Score And Rank # calculating the rank according to topsis score # Writing the csv # print(" Writing Result to CSV...\n") # print(" Successfully Terminated")