pyMachDM 0.1.0__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.
Files changed (84) hide show
  1. pymachdm/ANN_weights/1.Weld_Beam_MachineDM.joblib +0 -0
  2. pymachdm/ANN_weights/10.DTLZ7_MachineDM.joblib +0 -0
  3. pymachdm/ANN_weights/11.DTLZ7_MachineDM.joblib +0 -0
  4. pymachdm/ANN_weights/12.MW8_MachineDM.joblib +0 -0
  5. pymachdm/ANN_weights/13.MW8_MachineDM.joblib +0 -0
  6. pymachdm/ANN_weights/14.WAVY_3Obj_MachineDM.joblib +0 -0
  7. pymachdm/ANN_weights/15.FLOW_3Obj_MachineDM.joblib +0 -0
  8. pymachdm/ANN_weights/16.DPF4_MachineDM.joblib +0 -0
  9. pymachdm/ANN_weights/17.DPF4_MachineDM.joblib +0 -0
  10. pymachdm/ANN_weights/18.River_MachineDM.joblib +0 -0
  11. pymachdm/ANN_weights/19.River_MachineDM.joblib +0 -0
  12. pymachdm/ANN_weights/2.OSY_2Obj_MachineDM.joblib +0 -0
  13. pymachdm/ANN_weights/20.C2DTLZ2_MachineDM.joblib +0 -0
  14. pymachdm/ANN_weights/21.C2DTLZ2_MachineDM.joblib +0 -0
  15. pymachdm/ANN_weights/22.Knee_5Obj_MachineDM.joblib +0 -0
  16. pymachdm/ANN_weights/23.WATER_MachineDM.joblib +0 -0
  17. pymachdm/ANN_weights/24.WATER_MachineDM.joblib +0 -0
  18. pymachdm/ANN_weights/25.Clutch_MachineDM.joblib +0 -0
  19. pymachdm/ANN_weights/26.Clutch_MachineDM.joblib +0 -0
  20. pymachdm/ANN_weights/27.NIMBUS_MachineDM.joblib +0 -0
  21. pymachdm/ANN_weights/28.NIMBUS_MachineDM.joblib +0 -0
  22. pymachdm/ANN_weights/29.DTLZ2_8Obj_MachineDM.joblib +0 -0
  23. pymachdm/ANN_weights/3.ZDT2_2Obj_MachineDM.joblib +0 -0
  24. pymachdm/ANN_weights/30.GAA_10Obj_MachineDM.joblib +0 -0
  25. pymachdm/ANN_weights/4.Crash_MachineDM.joblib +0 -0
  26. pymachdm/ANN_weights/4.ZDT3_2Obj_MachineDM.joblib +0 -0
  27. pymachdm/ANN_weights/4a.ZDT3_2Obj_MachineDM.joblib +0 -0
  28. pymachdm/ANN_weights/5.WAVY_2Obj_MachineDM.joblib +0 -0
  29. pymachdm/ANN_weights/6.WAVY_2Obj_MachineDM.joblib +0 -0
  30. pymachdm/ANN_weights/7.Carside_MachineDM.joblib +0 -0
  31. pymachdm/ANN_weights/8.Carside_MachineDM.joblib +0 -0
  32. pymachdm/ANN_weights/9.FLOWER_3Obj_MachineDM.joblib +0 -0
  33. pymachdm/__init__.py +71 -0
  34. pymachdm/ann/__init__.py +16 -0
  35. pymachdm/ann/multioutput_class.py +115 -0
  36. pymachdm/ann/multioutput_reg.py +110 -0
  37. pymachdm/imcdm_methods/__init__.py +25 -0
  38. pymachdm/imcdm_methods/guess_start.py +46 -0
  39. pymachdm/imcdm_methods/guess_sub.py +49 -0
  40. pymachdm/imcdm_methods/mod_guess_start.py +47 -0
  41. pymachdm/imcdm_methods/mod_guess_sub.py +47 -0
  42. pymachdm/imcdm_methods/nimbus_inter.py +64 -0
  43. pymachdm/imcdm_methods/nimbus_start.py +48 -0
  44. pymachdm/imcdm_methods/nimbus_sub.py +56 -0
  45. pymachdm/imcdm_methods/stem_start.py +47 -0
  46. pymachdm/imcdm_methods/stem_sub.py +51 -0
  47. pymachdm/imcdm_methods/stom_start.py +46 -0
  48. pymachdm/imcdm_methods/stom_sub.py +47 -0
  49. pymachdm/machdm_imcdm/__init__.py +4 -0
  50. pymachdm/machdm_imcdm/machdm_all.py +771 -0
  51. pymachdm/machdm_imcdm/machine_dm.py +124 -0
  52. pymachdm/pareto/__init__.py +3 -0
  53. pymachdm/pareto/pareto_analyser.py +162 -0
  54. pymachdm/plots/__init__.py +7 -0
  55. pymachdm/plots/plot_2d_scatter.py +57 -0
  56. pymachdm/plots/plot_3d_scatter.py +91 -0
  57. pymachdm/plots/plot_pcp.py +93 -0
  58. pymachdm/plots/plot_radviz.py +496 -0
  59. pymachdm/plots/plot_tsne.py +369 -0
  60. pymachdm/problems/__init__.py +4 -0
  61. pymachdm/problems/problem_factory.py +879 -0
  62. pymachdm/problems/symbolic_problem_factory.py +696 -0
  63. pymachdm/run_machdm.py +232 -0
  64. pymachdm/soo_aasf/__init__.py +7 -0
  65. pymachdm/soo_aasf/guess_asf.py +99 -0
  66. pymachdm/soo_aasf/mod_guess_asf.py +112 -0
  67. pymachdm/soo_aasf/nimbus_asf.py +104 -0
  68. pymachdm/soo_aasf/stem_asf.py +99 -0
  69. pymachdm/soo_aasf/stom_asf.py +81 -0
  70. pymachdm/utils/__init__.py +21 -0
  71. pymachdm/utils/auto_tradeoff_stom.py +34 -0
  72. pymachdm/utils/compute_lambda.py +71 -0
  73. pymachdm/utils/compute_lambda_with_g.py +85 -0
  74. pymachdm/utils/cos_sim.py +8 -0
  75. pymachdm/utils/generate_ref_dirs.py +6 -0
  76. pymachdm/utils/predict_best.py +45 -0
  77. pymachdm/utils/predict_best2.py +62 -0
  78. pymachdm/utils/predict_prob.py +67 -0
  79. pymachdm/utils/predict_rank.py +47 -0
  80. pymachdm-0.1.0.dist-info/LICENSE +21 -0
  81. pymachdm-0.1.0.dist-info/METADATA +223 -0
  82. pymachdm-0.1.0.dist-info/RECORD +84 -0
  83. pymachdm-0.1.0.dist-info/WHEEL +5 -0
  84. pymachdm-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,124 @@
1
+ from pymachdm.pareto.pareto_analyser import ParetoAnalyzer
2
+ import numpy as np
3
+ from pymachdm.ann.multioutput_class import MultiOutputANN
4
+ from pymachdm.ann.multioutput_reg import MultiOutputANNRegressor
5
+
6
+ class MachineDM:
7
+ def __init__(self,
8
+ problem=None,
9
+ Delta=0.1,
10
+ Alpha=0.1,
11
+ ref_point=None,
12
+ file_path=None,
13
+ MOO_algo="nsga3",
14
+ n_gen=200,
15
+ pop_size=1000,
16
+ parts=7,
17
+ epochs=200,
18
+ batch_size=32,
19
+ hidden_layers=None,
20
+ learn_rate=0.001,
21
+ l2_reg=0.0001,
22
+ RNG=42):
23
+
24
+ if hidden_layers is None:
25
+ hidden_layers = [128, 64, 32, 16]
26
+
27
+ # Store inputs
28
+ self.problem = problem
29
+ self.Delta = Delta
30
+ self.Alpha = Alpha
31
+ self.ref_point = ref_point
32
+ self.file_path = file_path
33
+ self.algo = MOO_algo.lower()
34
+ self.n_gen = n_gen
35
+ self.pop_size = pop_size
36
+ self.parts = parts
37
+ self.epochs = epochs
38
+ self.batch_size = batch_size
39
+ self.hidden_layers = hidden_layers
40
+ self.learn_rate = learn_rate
41
+ self.l2_reg = l2_reg
42
+ self.RNG = RNG
43
+
44
+ print("=" * 100)
45
+ print(f"Building Machine-DM Setup: {self.problem.__class__.__name__}")
46
+ print("=" * 100)
47
+
48
+ # Load or generate Pareto data
49
+ if self.file_path is None:
50
+ self.pa = ParetoAnalyzer(self.problem,
51
+ data=None,
52
+ algo=self.algo,
53
+ das_danis_parts=self.parts,
54
+ pop_size=self.pop_size,
55
+ n_gen=self.n_gen,
56
+ seed=self.RNG)
57
+ else:
58
+ self.pa = ParetoAnalyzer(self.problem,
59
+ data=self.file_path,
60
+ algo=self.algo,
61
+ das_danis_parts=self.parts,
62
+ pop_size=self.pop_size,
63
+ n_gen=self.n_gen,
64
+ seed=self.RNG)
65
+
66
+ # Store Pareto sets
67
+ self.X = np.asarray(self.pa.X)
68
+ self.F = np.asarray(self.pa.F)
69
+
70
+ # Preferred solution (optional)
71
+ if self.ref_point is not None:
72
+ self.X_best, self.F_best, self.idx = self.pa.get_preferred_solution(self.ref_point)
73
+ else:
74
+ self.X_best = None
75
+ self.F_best = None
76
+ self.idx = None
77
+
78
+ print("=" * 100)
79
+ print("Pareto Summary")
80
+ print("=" * 100)
81
+ self.pa.summary()
82
+
83
+ # Problem properties
84
+ self.ideal_point = self.pa.ideal_point
85
+ self.nadir_point = self.pa.nadir_point
86
+ self.n_vars = self.problem.n_var
87
+ self.n_obj = self.problem.n_obj
88
+
89
+ # Class and parameter data generation
90
+ self.Out_Class, self.Out_Class_Vec, self.Out_Param = self.pa._data_generation(
91
+ self.F,
92
+ self.ref_point,
93
+ self.Delta,
94
+ self.Alpha
95
+ )
96
+
97
+ # Train Classifier (ANN_1)
98
+ print("=" * 100)
99
+ print("ANN 1: Class Predictor")
100
+ print("=" * 100)
101
+ self.ANN_1 = MultiOutputANN(hidden_layers=self.hidden_layers)
102
+ self.ANN_1.fit(self.X, self.Out_Class,
103
+ epochs=self.epochs,
104
+ batch_size=self.batch_size)
105
+
106
+ # Train Parameter Predictor (ANN_2)
107
+ print("=" * 100)
108
+ print("ANN 2: Parameter Predictor")
109
+ print("=" * 100)
110
+ self.ANN_2 = MultiOutputANNRegressor(hidden_layers=self.hidden_layers,
111
+ lr=self.learn_rate,
112
+ l2_reg=self.l2_reg)
113
+ self.ANN_2.fit(self.X, self.Out_Param,
114
+ epochs=self.epochs,
115
+ batch_size=self.batch_size)
116
+
117
+ print("=" * 100)
118
+ print(f"MachineDM Setup Complete: {self.problem.__class__.__name__}")
119
+ print("=" * 100)
120
+
121
+ # Provide accessor (optional)
122
+ def get_models(self):
123
+ """Return pa, ANN_1, ANN_2 for external use."""
124
+ return self.pa, self.ANN_1, self.ANN_2
@@ -0,0 +1,3 @@
1
+ from .pareto_analyser import ParetoAnalyzer
2
+
3
+ __all__ = ["ParetoAnalyzer"]
@@ -0,0 +1,162 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from pymoo.algorithms.moo.nsga2 import NSGA2
4
+ from pymoo.algorithms.moo.nsga3 import NSGA3
5
+ from pymoo.util.ref_dirs import get_reference_directions
6
+ from pymoo.optimize import minimize
7
+
8
+ class ParetoAnalyzer:
9
+ def __init__(self, problem, data=None, algo="nsga2", das_danis_parts=None, pop_size=100, n_gen=200, seed=1):
10
+ """
11
+ problem : instance of pymoo Problem (can have constraints)
12
+ data : tuple (F, X), or path to CSV/XLSX file, or None
13
+ algo : "nsga2" or "nsga3"
14
+ pop_size, n_gen : evolutionary algorithm parameters
15
+ seed : random seed for reproducibility
16
+ """
17
+ self.problem = problem
18
+ self.pop_size = pop_size
19
+ self.n_gen = n_gen
20
+ self.algo_name = algo.lower()
21
+ self.seed = seed
22
+ self.parts = das_danis_parts
23
+
24
+ # --- Data handling ---
25
+ if data is not None:
26
+ if isinstance(data, (tuple, list)):
27
+ # Case 1: data = (F, X)
28
+ self.X, self.F = data
29
+ print("✅ Using provided Pareto data (tuple).")
30
+
31
+ elif isinstance(data, str):
32
+ # Case 2: data is a path to a CSV or Excel file
33
+ print(f"📂 Reading data from file: {data}")
34
+ self.X, self.F = self._load_data_from_file(data)
35
+ print("✅ Extracted Pareto data from file.")
36
+
37
+ else:
38
+ raise ValueError("Unsupported data format. Provide (F, X) tuple or file path.")
39
+ else:
40
+ # Case 3: generate Pareto data using chosen algorithm
41
+ print(f"⚙️ Generating Pareto-optimal data using {self.algo_name.upper()}...")
42
+ self.X, self.F = self._generate_pareto_data()
43
+ print("✅ Pareto data generated.")
44
+
45
+ # --- Ideal & Nadir points ---
46
+ self.ideal_point = np.min(self.F, axis=0)
47
+ self.nadir_point = np.max(self.F, axis=0)
48
+
49
+ # ------------------------------------------------------------------------
50
+ def _load_data_from_file(self, filepath):
51
+ """Load F and X from CSV/XLSX using n_var and n_obj of the problem."""
52
+ if filepath.endswith(".csv"):
53
+ df = pd.read_csv(filepath)
54
+ elif filepath.endswith((".xls", ".xlsx")):
55
+ df = pd.read_excel(filepath)
56
+ else:
57
+ raise ValueError("File must be CSV or Excel (.csv/.xls/.xlsx)")
58
+
59
+ df = df.dropna(axis=0, how='any').reset_index(drop=True)
60
+ n_var, n_obj = self.problem.n_var, self.problem.n_obj
61
+
62
+ if df.shape[1] < n_var + n_obj:
63
+ raise ValueError(f"Data file has insufficient columns. Expected at least {n_var + n_obj} columns.")
64
+
65
+ X = df.iloc[:, :n_var].to_numpy()
66
+ F = df.iloc[:, n_var:n_var + n_obj].to_numpy()
67
+ return X, F
68
+
69
+ # ------------------------------------------------------------------------
70
+ def _generate_pareto_data(self):
71
+ """Generate Pareto-optimal solutions using NSGA-II or NSGA-III."""
72
+ if self.algo_name == "nsga2":
73
+ algorithm = NSGA2(pop_size=self.pop_size)
74
+
75
+ elif self.algo_name == "nsga3":
76
+ ref_dirs = get_reference_directions("das-dennis",
77
+ n_dim=self.problem.n_obj, n_partitions=self.parts)
78
+ algorithm = NSGA3(ref_dirs=ref_dirs)
79
+
80
+ else:
81
+ raise ValueError("Unsupported algorithm. Choose 'nsga2' or 'nsga3'.")
82
+
83
+ res = minimize(self.problem,
84
+ algorithm,
85
+ ('n_gen', self.n_gen),
86
+ seed=self.seed,
87
+ verbose=False)
88
+ return res.X, res.F
89
+
90
+ # ------------------------------------------------------------------------
91
+ def compute_asf(self, ref_point, rho=1e-3):
92
+ """Compute ASF (Achievement Scalarizing Function) values for all Pareto points."""
93
+ F_norm = (self.F - self.ideal_point) / (ref_point - self.ideal_point + 1e-12)
94
+ ref_norm = (self.F) / (self.nadir_point - self.ideal_point + 1e-12)
95
+ asf_vals = np.max(F_norm, axis=1) + rho * np.sum(F_norm, axis=1)
96
+ return asf_vals
97
+
98
+ def get_preferred_solution(self, ref_point, rho=1e-3):
99
+ """Return (X*, F*, index) minimizing the ASF."""
100
+ asf_vals = self.compute_asf(ref_point, rho)
101
+ idx_best = np.argmin(asf_vals)
102
+ return self.X[idx_best], self.F[idx_best], idx_best
103
+
104
+
105
+ def _data_generation(self, f, ref_point, Delta, Alpha):
106
+ f = self.F
107
+ Num_sol = len(self.F); M = len(ref_point)
108
+ Out_Class = np.zeros([Num_sol,M])
109
+ Out_Class_Vec = np.zeros([Num_sol,4])
110
+ Out_Param = np.zeros([Num_sol,M])
111
+
112
+ for i in range(0,Num_sol):
113
+ Out_Class[i,:], Out_Class_Vec[i,:], Out_Param[i,:] = self.classification(f[i,:], ref_point, Delta, Alpha)
114
+ return Out_Class, Out_Class_Vec, Out_Param
115
+
116
+
117
+ def classification(self,f,ref_point, Delta, Alpha):
118
+ Fin_X, Fin_F, idx = self.get_preferred_solution(ref_point, rho=1e-3)
119
+ eps = ref_point; delta = Delta*(self.nadir_point-self.ideal_point); d = Fin_F
120
+ M = len(Fin_F); alpha = Alpha*np.ones(M);
121
+ Class = np.zeros(M); param = np.zeros(M); V = np.zeros(4)
122
+ for i in range(0,M):
123
+ if(abs(f[i]-Fin_F[i])<=0.5*delta[i]):
124
+ Class[i] = 3
125
+ V[2] = V[2] + 1
126
+ param[i] = f[i] + 0.5*delta[i] *(-1 + 2*np.random.rand(1))
127
+ else:
128
+ if(f[i]>Fin_F[i]):
129
+ if(f[i]>=eps[i]):
130
+ Class[i] = 1
131
+ V[0] = V[0] + 1
132
+ DEL1 = alpha[i]*(self.nadir_point[i] - self.ideal_point[i])
133
+ DEL2 = f[i] - Fin_F[i]
134
+ DEL = np.min(np.array([DEL1,DEL2]))
135
+ param[i] = f[i] - DEL + alpha[i]*DEL *(-1 + 2*np.random.rand(1))
136
+
137
+ if(f[i]<eps[i]):
138
+ Class[i] = 2
139
+ V[1] = V[1] + 1
140
+ DEL1 = alpha[i]*(self.nadir_point[i] - self.ideal_point[i])
141
+ DEL2 = f[i] - Fin_F[i]
142
+ DEL = np.min(np.array([DEL1,DEL2]))
143
+ param[i] = f[i] - DEL + alpha[i]*DEL *(-1 + 2*np.random.rand(1))
144
+
145
+ if(f[i]<Fin_F[i]):
146
+ Class[i] = 4
147
+ V[3] = V[3] + 1
148
+ DEL1 = alpha[i]*(self.nadir_point[i] - self.ideal_point[i])
149
+ DEL2 = Fin_F[i] - f[i]
150
+ DEL = np.min(np.array([DEL1,DEL2]))
151
+ param[i] = f[i] + DEL + DEL*alpha[i] *(-1 + 2*np.random.rand(1))
152
+
153
+ return Class, V, param
154
+
155
+ def summary(self):
156
+ """Print problem and Pareto front info."""
157
+ print(f"Algorithm: {self.algo_name.upper()}")
158
+ print(f"Problem: {self.problem.__class__.__name__}")
159
+ print(f"Ideal Point: {self.ideal_point}")
160
+ print(f"Nadir Point: {self.nadir_point}")
161
+ print(f"Number of Pareto Points: {len(self.F)}")
162
+
@@ -0,0 +1,7 @@
1
+ from .plot_2d_scatter import plot_2D
2
+ from .plot_3d_scatter import plot_scatter_3D
3
+ from .plot_pcp import make_pcp_iter
4
+ from .plot_radviz import get_labels, make_radviz_iter
5
+ from .plot_tsne import make_tsne_iter
6
+
7
+ __all__ = ["plot_2D", "plot_scatter_3D", "make_pcp_iter", "get_labels", "make_radviz_iter", "make_tsne_iter"]
@@ -0,0 +1,57 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+
5
+ # ============================================================
6
+ # 1. 2D Scatter Plot for MCDM Iterations
7
+ # ============================================================
8
+
9
+ def plot_2D(pf,idx, NIM_Start_F1,NIM_iter_F,NIM_inter_F,NIM_F,ref_point,Delta,location):
10
+ ideal_point = np.min(pf,axis=0); nadir_point = np.max(pf,axis=0);
11
+ eps = ref_point; delta = Delta*(nadir_point-ideal_point); d = pf[idx,:]; Fin_F = d;
12
+ fig, ax = plt.subplots(figsize=(5, 5))
13
+ plt.scatter(pf[:, 0], pf[:, 1], s=10, label='Pareto Front', edgecolor='k', facecolor='w', alpha=1)
14
+ plt.scatter(NIM_Start_F1[:,0], NIM_Start_F1[:,1], s=75, label='Start Point', edgecolor='k', facecolor='k', alpha=1)
15
+
16
+ plt.scatter(NIM_iter_F[:,0], NIM_iter_F[:,1], s=75, edgecolor='k', facecolor='g', alpha=1)
17
+ if(np.size(NIM_inter_F,0)>0):
18
+ plt.scatter(NIM_inter_F[:,0], NIM_inter_F[:,1], s=75, edgecolor='k', facecolor='m', alpha=1)
19
+ plt.scatter(pf[idx, 0], pf[idx, 1], s=75, label='Target Solution', edgecolor='k', facecolor='r', alpha=1)
20
+
21
+ plt.axvline(x=eps[0], color='r', linewidth=1.5, linestyle=':')
22
+
23
+ plt.axvline(x=Fin_F[0]+0.5*delta[0], color='y', linewidth=1.5, linestyle=':')
24
+ plt.axvline(x=Fin_F[0]-0.5*delta[0], color='y', linewidth=1.5, linestyle=':')
25
+
26
+ plt.axvline(x=d[0], color='g', linewidth=1.5, linestyle=':')
27
+
28
+ plt.axhline(y=eps[1], color='r', linewidth=1.5, linestyle=':')
29
+
30
+ plt.axhline(y=Fin_F[1]+0.5*delta[1], color='y', linewidth=1.5, linestyle=':')
31
+ plt.axhline(y=Fin_F[1]-0.5*delta[1], color='y', linewidth=1.5, linestyle=':')
32
+
33
+ plt.axhline(y=d[1], color='g', linewidth=1.5, linestyle=':')
34
+
35
+ sc2 = plt.scatter(ref_point[0],ref_point[1], s=150, marker='*',edgecolor='k',facecolor='k',alpha=1)
36
+ sc3 = plt.scatter(ideal_point[0],ideal_point[1],s=80,edgecolor='k',facecolor='k',alpha=1)
37
+
38
+ plt.plot([ideal_point[0], ref_point[0]], [ideal_point[1], ref_point[1]], 'bo', linestyle="--", linewidth=0.75)
39
+ plt.plot([ideal_point[0]], [ideal_point[1]], 'mo', linestyle="--")
40
+ plt.text(0.95*ref_point[0], 1.05*ref_point[1], "$R$", fontsize=14)
41
+ plt.text(ideal_point[0], ideal_point[1], "$O$", fontsize=14)
42
+
43
+ c = 0.035*(nadir_point-ideal_point)
44
+ labels = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']
45
+ for (x, y), label in zip(NIM_F, labels):
46
+ plt.text(x+c[0], y+c[1], label, fontsize=14, ha='center', va='center', color='blue')
47
+ if(len(NIM_inter_F)>0):
48
+ plt.legend(["Pareto Front", "Start Point", "Alter. Solns.", "Inter. Solns.", "Preferred Soln."],
49
+ loc ="upper center",fontsize=10)
50
+ else:
51
+ plt.legend(["Pareto Front", "Start Point", "Alter. Solns.", "Preferred Soln."],
52
+ loc =location, fontsize=10)
53
+
54
+ plt.xlabel('$f_1$',fontsize=14)
55
+ plt.ylabel('$f_2$',fontsize=14)
56
+ plt.grid(color='k', linestyle='--', linewidth=1, alpha=0.15)
57
+ return fig, ax
@@ -0,0 +1,91 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+
4
+ def plot_scatter_3D(res, idx, NIM_Start_F1, NIM_iter_F, NIM_inter_F, NIM_F, ref_point,
5
+ location=None, elev=30, azim=45, c=None, figsize=(9, 9)):
6
+ # --- Helper: ensure 2D arrays ---
7
+ def to_2d(arr):
8
+ arr = np.array(arr)
9
+ if arr.ndim == 1:
10
+ arr = arr.reshape(1, -1)
11
+ return arr
12
+
13
+ pf = to_2d(res.F)
14
+ ideal_point = np.min(pf, axis=0)
15
+ NIM_Start_F1 = to_2d(NIM_Start_F1)
16
+ NIM_iter_F = to_2d(NIM_iter_F)
17
+ NIM_inter_F = to_2d(NIM_inter_F)
18
+ NIM_F = to_2d(NIM_F)
19
+ ref_point = np.array(ref_point).reshape(1, -1)
20
+
21
+ # --- Create figure and 3D axis ---
22
+ fig = plt.figure(figsize=figsize)
23
+ ax = fig.add_subplot(111, projection='3d')
24
+
25
+ # --- Pareto Front ---
26
+ if pf.size > 0:
27
+ ax.scatter(pf[:, 0], pf[:, 1], pf[:, 2],
28
+ s=10, edgecolor='k', facecolor='w', alpha=0.15, label='Pareto Front')
29
+ ax.scatter(pf[idx, 0], pf[idx, 1], pf[idx, 2],
30
+ s=75, edgecolor='k', facecolor='r', alpha=1.0, label='Pref. Soln.')
31
+
32
+ # --- Start Point ---
33
+ if NIM_Start_F1.size > 0:
34
+ ax.scatter(NIM_Start_F1[:, 0], NIM_Start_F1[:, 1], NIM_Start_F1[:, 2],
35
+ s=75, edgecolor='k', facecolor='k', alpha=1, label='Start Point')
36
+
37
+ # --- Iterative/Subproblem Solutions ---
38
+ if NIM_iter_F.size > 0:
39
+ ax.scatter(NIM_iter_F[:, 0], NIM_iter_F[:, 1], NIM_iter_F[:, 2],
40
+ s=75, edgecolor='k', facecolor='g', alpha=1, label='Alt. Solns.')
41
+
42
+ # --- Intermediate Solutions ---
43
+ if NIM_inter_F.size > 0:
44
+ ax.scatter(NIM_inter_F[:, 0], NIM_inter_F[:, 1], NIM_inter_F[:, 2],
45
+ s=75, edgecolor='k', facecolor='m', alpha=1, label='Inter. Solns.')
46
+
47
+ # --- Ideal and Reference Points ---
48
+ ax.plot([ideal_point[0], ref_point[0, 0]],
49
+ [ideal_point[1], ref_point[0, 1]],
50
+ [ideal_point[2], ref_point[0, 2]],
51
+ 'b--')
52
+
53
+ ax.scatter([ideal_point[0]], [ideal_point[1]], [ideal_point[2]], facecolor='m', edgecolor='k',
54
+ marker='o', s=80, label='Ideal Point')
55
+ ax.text(ideal_point[0] - 0.02, ideal_point[1], ideal_point[2], "$O$", fontsize=14, color='k')
56
+
57
+ ax.scatter(ref_point[:, 0], ref_point[:, 1], ref_point[:, 2], facecolor='b', edgecolor='k',
58
+ marker='*', s=150, label='Reference Point')
59
+ ax.text(ref_point[0, 0] + 0.02, ref_point[0, 1], ref_point[0, 2], "$R$", fontsize=14, color='k')
60
+
61
+ # --- Label NIM solutions ---
62
+ if c is None:
63
+ c = np.array([0.02, 0.02, 0.02]) # default small offset
64
+ labels = [chr(i) for i in range(65, 65 + len(NIM_F))] # A, B, C, ...
65
+ for (x, y, z), label in zip(NIM_F, labels):
66
+ ax.text(x + c[0], y + c[1], z + c[2], label,
67
+ fontsize=12, color="blue", ha='center', va='center')
68
+
69
+ # --- Labels, Grid, and View ---
70
+ ax.set_xlabel('$f_1$', fontsize=12)
71
+ ax.set_ylabel('$f_2$', fontsize=12)
72
+ ax.set_zlabel('$f_3$', fontsize=12)
73
+ ax.grid(color='k', linestyle='--', linewidth=1, alpha=0.25)
74
+ ax.view_init(elev=elev, azim=azim)
75
+
76
+ # --- Equal Aspect Ratio ---
77
+ # limits = np.array([ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()])
78
+ # center = np.mean(limits, axis=1)
79
+ # radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))
80
+ # ax.set_xlim3d([center[0] - radius, center[0] + radius])
81
+ # ax.set_ylim3d([center[1] - radius, center[1] + radius])
82
+ # ax.set_zlim3d([center[2] - radius, center[2] + radius])
83
+
84
+ # --- Legend ---
85
+ if location is None:
86
+ location = (0.15, 0.55)
87
+ ax.legend(loc=location, fontsize=10)
88
+
89
+ plt.tight_layout()
90
+ plt.show()
91
+ return fig, ax
@@ -0,0 +1,93 @@
1
+ import matplotlib.pyplot as plt
2
+ import numpy as np
3
+
4
+ def make_pcp_iter(pf, idx, STEM_Start_F, STEM_iter_F, NIM_F, figsize, STEM_inter_F=None):
5
+ n_obj = pf.shape[1]
6
+ x = np.arange(n_obj + 1)
7
+ x_inter = np.arange(n_obj)
8
+ if STEM_inter_F is None:
9
+ data1 = np.vstack([pf, STEM_Start_F, STEM_iter_F])
10
+ else:
11
+ data1 = np.vstack([pf, STEM_Start_F, STEM_iter_F, STEM_inter_F])
12
+ data1_min = data1.min(axis=0)
13
+ data1_max = data1.max(axis=0)
14
+
15
+ # Normalize PF
16
+ pf_norm = np.concatenate([(pf - data1_min) / (data1_max - data1_min),
17
+ np.ones([len(pf), 1])], axis=1)
18
+ STEM_Target_FN = np.concatenate([(pf[idx] - data1_min) / (data1_max - data1_min),
19
+ np.array([1])])
20
+ STEM_Start_FN = np.concatenate([(STEM_Start_F - data1_min) / (data1_max - data1_min),
21
+ np.array([[0]])], axis=1)
22
+ ticks_orig = np.linspace(0.1, 0.9, len(STEM_iter_F))
23
+ # ticks_orig = ticks_def[1:len(STEM_iter_F)+1]
24
+ STEM_iter_FN = np.concatenate([(STEM_iter_F - data1_min) / (data1_max - data1_min),
25
+ ticks_orig.reshape(-1, 1)], axis=1)
26
+
27
+ # Optional intermediate set (no iteration numbers, exclude last axis)
28
+ indices = []
29
+ if STEM_inter_F is not None:
30
+ dtype = np.dtype((np.void, NIM_F.dtype.itemsize * NIM_F.shape[1]))
31
+ NIM_F_view = NIM_F.view(dtype).ravel()
32
+ NIM_inter_view = STEM_inter_F.view(dtype).ravel()
33
+ indices = np.array([np.where(NIM_F_view == row)[0][0] for row in NIM_inter_view])
34
+ STEM_inter_FN = (STEM_inter_F - data1_min) / (data1_max - data1_min)
35
+
36
+ # --- Main axis ---
37
+ fig, ax = plt.subplots(figsize= figsize)
38
+ for row in pf_norm:
39
+ ax.plot(x, row, color="gray", alpha=0.1, linewidth=0.25)
40
+ ax.plot([], [], color="gray", alpha=0.3, linewidth=1.5, label="Pareto Front")
41
+
42
+ ax.plot(x, STEM_Target_FN, color="red", alpha=1.0, linewidth=2.5, label="Pref. Soln.")
43
+ ax.plot(x, STEM_Start_FN[0], color="black", alpha=1.0, linewidth=2.5, label="Start Point")
44
+
45
+ # --- Secondary y-axis for iteration ---
46
+ ax_iter = ax.twinx()
47
+ ax_iter.set_ylim(0, 1)
48
+ ax_iter.set_ylabel("MCDM Steps", rotation=-90, labelpad=15)
49
+ ax_iter.spines["right"].set_position(("data", x[-1]))
50
+ ax_iter.yaxis.tick_right()
51
+ ax_iter.spines["right"].set_visible(True)
52
+ ax_iter.grid(False)
53
+
54
+ # --- Scale iteration lines visually ---
55
+ iter_ymin, iter_ymax = ax_iter.get_ylim()
56
+ iter_scale = 1 / (iter_ymax - iter_ymin)
57
+ STEM_iter_FN_scaled = STEM_iter_FN.copy()
58
+ STEM_iter_FN_scaled[:, -1] = (STEM_iter_FN[:, -1] - iter_ymin) * iter_scale
59
+
60
+ for i, row in enumerate(STEM_iter_FN_scaled):
61
+ if len(indices) > 0:
62
+ color = "magenta" if i in indices else "green"
63
+ else:
64
+ color = "green"
65
+ ax.plot(x, row, color=color, alpha=1.0, linewidth=1.0)
66
+ ax.plot([], [], color="green", alpha=1.0, linewidth=1.5, label="Alter. Solns.")
67
+ # ax.plot([], [], color="magenta", alpha=1.0, linewidth=1.5, label="Inter. Solns.")
68
+
69
+ # --- Format axes ---
70
+ ax.set_xticks(x)
71
+ ax.set_xticklabels([fr"$f_{{{i}}}$" for i in range(1, n_obj+1)] + ["Iteration"], fontsize=11)
72
+ ax.set_xlabel("Objectives", fontsize=11)
73
+ ax.set_ylabel("Normalized Objective Value", fontsize=11)
74
+ ax.grid(alpha=0.3)
75
+ ax.legend()
76
+
77
+ yticks_dense = np.arange(0, 1.2, 0.1)
78
+ ax.set_yticks(yticks_dense)
79
+ yticks_iter1 = np.linspace(0.1275, 0.825, len(STEM_iter_F))
80
+ yticks_iter = np.array([0.045, *yticks_iter1, 0.92])
81
+ labels_iter = ["Start Point"] + [f"Iteration: {i}" for i in range(1, len(STEM_iter_F)+1)] + ["Pref. Soln."]
82
+ ax_iter.set_yticks(yticks_iter)
83
+ ax_iter.set_yticklabels(labels_iter)
84
+
85
+ # Make outer boundary (spines) light
86
+ for axis in [ax, ax_iter]:
87
+ for spine in axis.spines.values():
88
+ spine.set_color((0.15, 0.15, 0.15, 0.25))
89
+ spine.set_linewidth(0.1)
90
+
91
+ plt.tight_layout()
92
+ plt.show()
93
+ return fig, ax