topsis-pranshu-102313009 1.0.3__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,97 +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
- # Keep first column as alternative name
43
- alternatives = df.iloc[:, 0]
35
+ data_df = df.iloc[:, 1:].copy()
44
36
 
45
- # Automatically select ONLY numeric columns (criteria)
46
- data = df.iloc[:, 1:].select_dtypes(include=[np.number])
37
+ try:
38
+ data_df = data_df.apply(pd.to_numeric)
39
+ except:
40
+ error("From 2nd to last columns must contain numeric values only.")
41
+
42
+ if data_df.isnull().values.any():
43
+ error("Input data contains non-numeric or missing values.")
44
+
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]
47
52
 
48
- if data.shape[1] < 1:
49
- error("No numeric criteria columns found")
53
+ if len(weights) != num_cols or len(impacts) != num_cols:
54
+ error("Number of weights, impacts and criteria columns must be the same.")
50
55
 
51
- weights = list(map(float, weights.split(",")))
52
- impacts = impacts.split(",")
56
+ if not all(i in ["+", "-"] for i in impacts):
57
+ error("Impacts must be either '+' or '-'.")
53
58
 
54
- if len(weights) != len(impacts) or len(weights) != data.shape[1]:
55
- error(
56
- f"Weights ({len(weights)}), impacts ({len(impacts)}) "
57
- f"and criteria ({data.shape[1]}) count mismatch"
58
- )
59
+ matrix = data_df.values
60
+ rss = np.sqrt(np.sum(matrix ** 2, axis=0))
59
61
 
60
- if not all(i in ['+', '-'] for i in impacts):
61
- error("Impacts must be + or -")
62
+ if (rss == 0).any():
63
+ error("Normalization failed due to zero variance column.")
62
64
 
63
- # ---------- TOPSIS CALCULATION ----------
64
- norm = data / np.sqrt((data ** 2).sum())
65
- weighted = norm * weights
65
+ normalized_matrix = matrix / rss
66
+ weighted_matrix = normalized_matrix * weights
66
67
 
67
68
  ideal_best = []
68
69
  ideal_worst = []
69
70
 
70
- for i, impact in enumerate(impacts):
71
- if impact == '+':
72
- ideal_best.append(weighted.iloc[:, i].max())
73
- 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]))
74
75
  else:
75
- ideal_best.append(weighted.iloc[:, i].min())
76
- 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]))
77
78
 
78
79
  ideal_best = np.array(ideal_best)
79
80
  ideal_worst = np.array(ideal_worst)
80
81
 
81
- d_pos = np.sqrt(((weighted - ideal_best) ** 2).sum(axis=1))
82
- d_neg = np.sqrt(((weighted - ideal_worst) ** 2).sum(axis=1))
83
-
84
- score = d_neg / (d_pos + d_neg)
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))
85
84
 
86
- result = pd.DataFrame({
87
- df.columns[0]: alternatives,
88
- "Topsis Score": score,
89
- "Rank": score.rank(ascending=False).astype(int)
90
- })
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)
91
87
 
92
- result.to_csv(output_file, index=False)
93
- print("TOPSIS completed successfully")
88
+ df["Topsis Score"] = performance_score
89
+ df["Rank"] = df["Topsis Score"].rank(ascending=False, method="min").astype(int)
94
90
 
91
+ df.to_csv(output_file, index=False)
92
+ print(f"Success: Result saved to {output_file}")
95
93
 
96
94
  if __name__ == "__main__":
97
95
  main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: topsis-pranshu-102313009
3
- Version: 1.0.3
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=px_u0knbzcvODV6e4RY53tNdIRJYIAvXeCdWqk05k0M,2827
3
- topsis_pranshu_102313009-1.0.3.dist-info/licenses/LICENSE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- topsis_pranshu_102313009-1.0.3.dist-info/METADATA,sha256=lUD3Bq2rjW39h-p150c43amkSFF91HUuYywMJFQv3nk,331
5
- topsis_pranshu_102313009-1.0.3.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
6
- topsis_pranshu_102313009-1.0.3.dist-info/entry_points.txt,sha256=jjw-fXzduRHvZc9NlWHV7aZzaHhK3En131ITtjs63Ag,54
7
- topsis_pranshu_102313009-1.0.3.dist-info/top_level.txt,sha256=uuGS33veOL0dkp49hZ522LxEG8fHjA3KmvAP3hNVm2M,15
8
- topsis_pranshu_102313009-1.0.3.dist-info/RECORD,,