topsis-pranshu-102313009 1.0.2__py3-none-any.whl → 1.0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
topsis_pranshu/topsis.py CHANGED
@@ -1,89 +1,95 @@
1
1
  import sys
2
+ import os
2
3
  import pandas as pd
3
4
  import numpy as np
4
- import os
5
-
6
5
 
7
6
  def error(msg):
8
7
  print(f"Error: {msg}")
9
8
  sys.exit(1)
10
9
 
11
-
12
10
  def main():
13
11
  if len(sys.argv) != 5:
14
- error("Usage: topsis <InputFile> <Weights> <Impacts> <OutputFile>")
12
+ error("Wrong number of parameters. Usage: python topsis.py <InputDataFile> <Weights> <Impacts> <OutputResultFileName>")
15
13
 
16
- input_file, weights, impacts, output_file = sys.argv[1:]
14
+ input_file = sys.argv[1]
15
+ weights_str = sys.argv[2]
16
+ impacts_str = sys.argv[3]
17
+ output_file = sys.argv[4]
17
18
 
18
19
  if not os.path.exists(input_file):
19
- error("Input file not found")
20
+ error(f"The file '{input_file}' was not found.")
20
21
 
21
- # ---------- READ FILE (CSV / XLSX) ----------
22
22
  try:
23
23
  if input_file.lower().endswith(".csv"):
24
- try:
25
- df = pd.read_csv(input_file, encoding="utf-8")
26
- except UnicodeDecodeError:
27
- df = pd.read_csv(input_file, encoding="latin1")
28
-
29
- elif input_file.lower().endswith(".xlsx"):
24
+ df = pd.read_csv(input_file)
25
+ elif input_file.lower().endswith(".xlsx") or input_file.lower().endswith(".xls"):
30
26
  df = pd.read_excel(input_file)
31
-
32
27
  else:
33
- error("Only .csv or .xlsx files are supported")
34
-
28
+ error("Unsupported file format. Use .csv or .xlsx")
35
29
  except Exception as e:
36
- error(f"Unable to read input file: {e}")
30
+ error(f"Error reading file: {e}")
37
31
 
38
- # ---------- VALIDATIONS ----------
39
32
  if df.shape[1] < 3:
40
- error("Input file must contain at least 3 columns")
33
+ error("Input file must contain three or more columns.")
41
34
 
42
- data = df.iloc[:, 1:]
35
+ data_df = df.iloc[:, 1:].copy()
43
36
 
44
37
  try:
45
- data = data.astype(float)
38
+ data_df = data_df.apply(pd.to_numeric)
46
39
  except:
47
- error("Columns from 2nd onward must be numeric")
40
+ error("From 2nd to last columns must contain numeric values only.")
48
41
 
49
- weights = list(map(float, weights.split(",")))
50
- impacts = impacts.split(",")
42
+ if data_df.isnull().values.any():
43
+ error("Input data contains non-numeric or missing values.")
51
44
 
52
- if len(weights) != len(impacts) or len(weights) != data.shape[1]:
53
- error("Weights, impacts and criteria count mismatch")
45
+ try:
46
+ weights = [float(w) for w in weights_str.split(",")]
47
+ impacts = impacts_str.split(",")
48
+ except:
49
+ error("Weights must be numeric and impacts must be comma-separated.")
50
+
51
+ num_cols = data_df.shape[1]
52
+
53
+ if len(weights) != num_cols or len(impacts) != num_cols:
54
+ error("Number of weights, impacts and criteria columns must be the same.")
54
55
 
55
- if not all(i in ['+', '-'] for i in impacts):
56
- error("Impacts must be + or -")
56
+ if not all(i in ["+", "-"] for i in impacts):
57
+ error("Impacts must be either '+' or '-'.")
57
58
 
58
- # ---------- TOPSIS CALCULATION ----------
59
- norm = data / np.sqrt((data ** 2).sum())
60
- weighted = norm * weights
59
+ matrix = data_df.values
60
+ rss = np.sqrt(np.sum(matrix ** 2, axis=0))
61
+
62
+ if (rss == 0).any():
63
+ error("Normalization failed due to zero variance column.")
64
+
65
+ normalized_matrix = matrix / rss
66
+ weighted_matrix = normalized_matrix * weights
61
67
 
62
68
  ideal_best = []
63
69
  ideal_worst = []
64
70
 
65
- for i, impact in enumerate(impacts):
66
- if impact == '+':
67
- ideal_best.append(weighted.iloc[:, i].max())
68
- ideal_worst.append(weighted.iloc[:, i].min())
71
+ for i in range(num_cols):
72
+ if impacts[i] == "+":
73
+ ideal_best.append(np.max(weighted_matrix[:, i]))
74
+ ideal_worst.append(np.min(weighted_matrix[:, i]))
69
75
  else:
70
- ideal_best.append(weighted.iloc[:, i].min())
71
- ideal_worst.append(weighted.iloc[:, i].max())
76
+ ideal_best.append(np.min(weighted_matrix[:, i]))
77
+ ideal_worst.append(np.max(weighted_matrix[:, i]))
72
78
 
73
79
  ideal_best = np.array(ideal_best)
74
80
  ideal_worst = np.array(ideal_worst)
75
81
 
76
- d_pos = np.sqrt(((weighted - ideal_best) ** 2).sum(axis=1))
77
- d_neg = np.sqrt(((weighted - ideal_worst) ** 2).sum(axis=1))
82
+ s_plus = np.sqrt(np.sum((weighted_matrix - ideal_best) ** 2, axis=1))
83
+ s_minus = np.sqrt(np.sum((weighted_matrix - ideal_worst) ** 2, axis=1))
78
84
 
79
- score = d_neg / (d_pos + d_neg)
85
+ total_dist = s_plus + s_minus
86
+ performance_score = np.divide(s_minus, total_dist, out=np.zeros_like(s_minus), where=total_dist != 0)
80
87
 
81
- df["Topsis Score"] = score
82
- df["Rank"] = score.rank(ascending=False).astype(int)
88
+ df["Topsis Score"] = performance_score
89
+ df["Rank"] = df["Topsis Score"].rank(ascending=False, method="min").astype(int)
83
90
 
84
91
  df.to_csv(output_file, index=False)
85
- print("TOPSIS completed successfully")
86
-
92
+ print(f"Success: Result saved to {output_file}")
87
93
 
88
94
  if __name__ == "__main__":
89
95
  main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: topsis-pranshu-102313009
3
- Version: 1.0.2
3
+ Version: 1.0.4
4
4
  Summary: TOPSIS command-line tool
5
5
  Author: Pranshu Goel
6
6
  Author-email: your@email.com
@@ -0,0 +1,8 @@
1
+ topsis_pranshu/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ topsis_pranshu/topsis.py,sha256=9DLi5NiwGBUL2lfzyueKkp2J-WHNgho9uTvCnnuRmdw,3092
3
+ topsis_pranshu_102313009-1.0.4.dist-info/licenses/LICENSE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ topsis_pranshu_102313009-1.0.4.dist-info/METADATA,sha256=HIvniGzrhyLNPATOj2WeUHTTDGW-1i-uF903fS1mbRk,331
5
+ topsis_pranshu_102313009-1.0.4.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
6
+ topsis_pranshu_102313009-1.0.4.dist-info/entry_points.txt,sha256=jjw-fXzduRHvZc9NlWHV7aZzaHhK3En131ITtjs63Ag,54
7
+ topsis_pranshu_102313009-1.0.4.dist-info/top_level.txt,sha256=uuGS33veOL0dkp49hZ522LxEG8fHjA3KmvAP3hNVm2M,15
8
+ topsis_pranshu_102313009-1.0.4.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- topsis_pranshu/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- topsis_pranshu/topsis.py,sha256=x9alE2B8ibz-OVDrfgDBE1czUW1493QpZr5R-ICMpqg,2516
3
- topsis_pranshu_102313009-1.0.2.dist-info/licenses/LICENSE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- topsis_pranshu_102313009-1.0.2.dist-info/METADATA,sha256=Fc7cHAt5tD9lBrntPWMusWv5JKjc5iUhIMnXGUd07YE,331
5
- topsis_pranshu_102313009-1.0.2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
6
- topsis_pranshu_102313009-1.0.2.dist-info/entry_points.txt,sha256=jjw-fXzduRHvZc9NlWHV7aZzaHhK3En131ITtjs63Ag,54
7
- topsis_pranshu_102313009-1.0.2.dist-info/top_level.txt,sha256=uuGS33veOL0dkp49hZ522LxEG8fHjA3KmvAP3hNVm2M,15
8
- topsis_pranshu_102313009-1.0.2.dist-info/RECORD,,