编辑代码

import numpy as np

def topsis(matrix, weights, impacts):
    # Normalize the decision matrix
    norm_matrix = matrix / np.sqrt((matrix ** 2).sum(axis=0))

    # Multiply the normalized matrix by the weights
    weighted_matrix = norm_matrix * weights

    # Determine the ideal and negative-ideal solutions
    ideal_best = np.max(weighted_matrix, axis=0) * impacts
    ideal_worst = np.min(weighted_matrix, axis=0) * impacts

    # Calculate the separation measures
    separation_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 solution
    closeness = separation_worst / (separation_best + separation_worst)

    # Rank the alternatives based on the closeness
    rank = np.argsort(closeness)[::-1] + 1

    return closeness, rank

# Example usage
    if __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 criterion
    weights = 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("Closeness to ideal solution:", closeness)
    print("Ranking of alternatives:", rank)