importnumpyasnpdeftopsis(matrix,weights,impacts):# Normalize the decision matrixnorm_matrix=matrix/np.sqrt((matrix**2).sum(axis=0))# Multiply the normalized matrix by the weightsweighted_matrix=norm_matrix*weights# Determine the ideal and negative-ideal solutionsideal_best=np.max(weighted_matrix,axis=0)*impactsideal_worst=np.min(weighted_matrix,axis=0)*impacts# Calculate the separation measuresseparation_best=np.sqrt(((weighted_matrix-ideal_best)**2).sum(axis=1))separation_worst=np.sqrt(((weighted_matrix-ideal_worst)**2).sum(axis=1))# Calculate the relative closeness to the ideal solutioncloseness=separation_worst/(separation_best+separation_worst)# Rank the alternatives based on the closenessrank=np.argsort(closeness)[::-1]+1returncloseness,rank# Example usageif__name__=="__main__":# Decision matrix (alternatives x criteria)matrix=np.array([
[7, 5, 8, 6, 8, 6],
[9, 7, 6, 4, 7, 8],
[6, 8, 5, 7, 6, 5],
[8, 6, 7, 5, 9, 7],
[5, 4, 9, 8, 5, 9],
[4, 9, 4, 9, 4, 4]
])# Weights for each criterionweights=np.array([0.35,0.2,0.1,0.08,0.12,0.05])# Impacts (+1 for benefit, -1 for cost)impacts=np.array([-1,-1,-1,-1,-1,-1])closeness,rank=topsis(matrix,weights,impacts)print("Closenesstoidealsolution:",closeness)print("Rankingofalternatives:",rank)