Skip to content

Commit bc7abd9

Browse files
authored
Added Pareto set drawing (#200)
1 parent de97b58 commit bc7abd9

File tree

7 files changed

+91
-30
lines changed

7 files changed

+91
-30
lines changed

examples/MCO_Grishagin_example.py

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from iOpt.output_system.listeners.static_painters import StaticPainterParetoListener
12
from problems.grishagin_mco import Grishagin_mco
23
from iOpt.solver import Solver
34
from iOpt.solver_parametrs import SolverParameters
@@ -18,6 +19,9 @@
1819
cfol = ConsoleOutputListener(mode='full')
1920
solver.add_listener(cfol)
2021

22+
sppl = StaticPainterParetoListener("Grishagin_mco_pareto.png")
23+
solver.add_listener(sppl)
24+
2125
sol = solver.solve()
2226

2327
# output of the Pareto set (coordinates - function values)

examples/MCO_Test1_example.py

+5-14
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from iOpt.solver_parametrs import SolverParameters
44

55
from iOpt.output_system.listeners.console_outputers import ConsoleOutputListener
6+
from iOpt.output_system.listeners.static_painters import StaticPainterParetoListener
67
import matplotlib.pyplot as plt
78

89
if __name__ == "__main__":
@@ -24,6 +25,10 @@
2425
cfol = ConsoleOutputListener(mode='full')
2526
solver.add_listener(cfol)
2627

28+
# Добавляем построение графика множества Парето y[0]-y[1]
29+
sppl = StaticPainterParetoListener("mco_test1_pareto.png")
30+
solver.add_listener(sppl)
31+
2732
# Решаем задачу
2833
sol = solver.solve()
2934

@@ -33,17 +38,3 @@
3338
print("size pareto set: ", len(var))
3439
for fvar, fval in zip(var, val):
3540
print(fvar, fval)
36-
37-
# Точки для построения
38-
# x1 = [trial.point.float_variables[0] for trial in sol.best_trials]
39-
# x2 = [trial.point.float_variables[1] for trial in sol.best_trials]
40-
41-
# plt.plot(x1, x2, 'ro')
42-
# plt.show()
43-
44-
# Точки для построения графика множества Парето y[0]-y[1]
45-
fv1 = [trial.function_values[0].value for trial in sol.best_trials]
46-
fv2 = [trial.function_values[1].value for trial in sol.best_trials]
47-
48-
plt.plot(fv1, fv2, 'ro')
49-
plt.show()

examples/Machine_learning/SVC/_2D/Example_SVC_2D_MCO_Transformators_State.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from iOpt.output_system.listeners.static_painters import StaticPainterNDListener
1+
from iOpt.output_system.listeners.static_painters import StaticPainterParetoListener
22
from iOpt.output_system.listeners.console_outputers import ConsoleOutputListener
33

44
from iOpt.solver import Solver
@@ -12,7 +12,7 @@
1212
# Для построения HV индекса
1313
# from pymoo.util.misc import stack
1414
# from pymoo.indicators.hv import HV
15-
import numpy as np
15+
# import numpy as np
1616

1717
def factory_dataset():
1818
x = []
@@ -34,13 +34,16 @@ def factory_dataset():
3434
kernel_coefficient_bound = {'low': -3, 'up': 1}
3535
problem = MCO_SVC_2D_Transformators_State.MCO_SVC_2D_Transformators_State(X, Y, regularization_value_bound,
3636
kernel_coefficient_bound)
37-
method_params = SolverParameters(r=np.double(2.0), iters_limit=50, number_of_parallel_points=1,
37+
method_params = SolverParameters(r=np.double(2.0), iters_limit=500, number_of_parallel_points=1,
3838
evolvent_density=12, number_of_lambdas=5)
3939
solver = Solver(problem=problem, parameters=method_params)
4040
# Добавляем вывод результатов в консоль
4141
cfol = ConsoleOutputListener(mode='full')
4242
solver.add_listener(cfol)
4343

44+
sppl = StaticPainterParetoListener("MCO_SVC_2D_Transformators_pareto.png")
45+
solver.add_listener(sppl)
46+
4447
# Решаем задачу
4548
sol = solver.solve()
4649

examples/Machine_learning/SVC/_2D/Problems/MCO_SVC_2D_Transformators_State.py

-5
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,6 @@ def __init__(self, x_dataset: np.ndarray, y_dataset: np.ndarray,
4242
self.upper_bound_of_float_variables = np.array([regularization_bound['up'], kernel_coefficient_bound['up']],
4343
dtype=np.double)
4444

45-
#self.cv = StratifiedKFold(shuffle=True, random_state=42)
46-
47-
48-
49-
5045
def calculateAllFunction(self, point: Point, function_values: np.ndarray(shape=(1), dtype=FunctionValue)) -> \
5146
np.ndarray(shape=(1), dtype=FunctionValue):
5247
"""

iOpt/output_system/listeners/static_painters.py

+31-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from iOpt.method.listener import Listener
22
from iOpt.method.method import Method
33
from iOpt.method.search_data import SearchData
4-
from iOpt.output_system.painters.static_painters import StaticPainter, StaticPainterND, DiscretePainter
4+
from iOpt.output_system.painters.static_painters import StaticPainter, StaticPainterND, DiscretePainter, StaticPainterPareto
55
from iOpt.solution import Solution
66

77

@@ -89,7 +89,7 @@ def __init__(self, file_name: str, path_for_saves="", indx=0, is_points_at_botto
8989
"""
9090
Constructor of the StaticPainterListener class
9191
92-
:param file_name: File name specifying the format for saving the image.
92+
:param file_name: File name specifying the format for saving the image.
9393
:param path_for_saves: The directory to save the image. If this parameter is not specified, the image is saved in the current working directory.
9494
is saved in the current working directory.
9595
:param indx: Index of the variable of the optimization problem. It is used in multivariate optimization.
@@ -133,9 +133,9 @@ class StaticPainterNDListener(Listener):
133133
def __init__(self, file_name: str, path_for_saves="", vars_indxs=[0, 1], mode='lines layers',
134134
calc='objective function'):
135135
"""
136-
Конструктор класса StaticPainterNDListener
136+
Constructor of the StaticPainterNDListener class
137137
138-
:param file_name: File name specifying the format for saving the image.
138+
:param file_name: File name specifying the format for saving the image.
139139
:param path_for_saves: The directory to save the image. If this parameter is not specified, the image is saved in the current working directory.
140140
is saved in the current working directory.
141141
:param vars_indxs: A pair of indices of the variables of the optimization problem for which the figure will be plotted.
@@ -167,3 +167,30 @@ def on_method_stop(self, search_data: SearchData,
167167
painter.paint_points()
168168
painter.paint_optimum()
169169
painter.save_image()
170+
171+
172+
class StaticPainterParetoListener(Listener):
173+
"""
174+
The StaticPainterParetoListener class is an event listener. It contains a method handler that produces an image as a
175+
image as a reaction to the method completion.
176+
It is used for multicriteria optimization
177+
"""
178+
179+
def __init__(self, file_name: str, path_for_saves="", criteria_indxs=[0, 1]):
180+
"""
181+
Constructor of the StaticPainterParetoListener class
182+
183+
:param file_name: File name specifying the format for saving the image.
184+
:param path_for_saves: The directory to save the image. If this parameter is not specified, the image is saved in the current working directory.
185+
is saved in the current working directory.
186+
:param criteria_indxs: A pair of indices of the criteria of the optimization problem for which the figure will be plotted.
187+
"""
188+
self.file_name = file_name
189+
self.path_for_saves = path_for_saves
190+
self.criteria_indxs = criteria_indxs
191+
192+
def on_method_stop(self, search_data: SearchData,
193+
solution: Solution, status: bool, ):
194+
painter = StaticPainterPareto(solution, self.criteria_indxs, self.path_for_saves, self.file_name)
195+
painter.paint_pareto()
196+
painter.save_image()

iOpt/output_system/painters/plotters/plotters.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,8 @@ def __init__(self, parameter_in_nd_problem, left_bound, right_bound):
243243

244244
self.fig, self.ax = plt.subplots(1, 1)
245245
self.ax.tick_params(axis='both', labelsize=8)
246-
self.ax.set_xlim([self.leftBound, self.rightBound])
246+
if self.leftBound != None and self.rightBound != None:
247+
self.ax.set_xlim([self.leftBound, self.rightBound])
247248

248249
def plot_by_grid(self, calculate, section, points_count=100):
249250
x = np.arange(self.leftBound, self.rightBound, (self.rightBound - self.leftBound) / points_count)
@@ -433,4 +434,12 @@ def plot_points(self, points, values, clr='blue', mrkr='o', mrkrs=4):
433434
self.ax.relim()
434435
self.ax.autoscale_view()
435436
self.fig.canvas.draw()
436-
self.fig.canvas.flush_events()
437+
self.fig.canvas.flush_events()
438+
439+
440+
class PlotterPareto(Plotter2D):
441+
def __init__(self):
442+
super().__init__(None, None, None)
443+
444+
def plot_pareto(self, first_criteria_values, second_criteria_values, clr='blue', mrkr='o', mrkrs=8):
445+
self.plot_points(first_criteria_values, second_criteria_values, clr, mrkr, mrkrs)

iOpt/output_system/painters/static_painters.py

+34-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from iOpt.method.search_data import SearchData, SearchDataItem
44
from iOpt.trial import Point, FunctionValue
55
from iOpt.solution import Solution
6-
from iOpt.output_system.painters.plotters.plotters import Plotter2D, Plotter3D, DisretePlotter
6+
from iOpt.output_system.painters.plotters.plotters import Plotter2D, Plotter3D, DisretePlotter, PlotterPareto
77
from iOpt.output_system.painters.painter import Painter
88

99
import matplotlib.pyplot as plt
@@ -282,4 +282,36 @@ def calculate_func(self, x):
282282
point = Point(x, [])
283283
fv = FunctionValue()
284284
fv = self.objFunc(point, fv)
285-
return fv.value
285+
return fv.value
286+
287+
288+
class StaticPainterPareto:
289+
def __init__(self,
290+
solution: Solution,
291+
criteria_indxs,
292+
path_for_saves,
293+
file_name
294+
):
295+
self.path_for_saves = path_for_saves
296+
self.file_name = file_name
297+
298+
# values of Pareto-efficient criteria with input indices
299+
self.first_criteria_values = [trial.function_values[criteria_indxs[0]].value for trial in solution.best_trials]
300+
self.second_criteria_values = [trial.function_values[criteria_indxs[1]].value for trial in solution.best_trials]
301+
302+
# definition of plotter
303+
self.plotter = PlotterPareto()
304+
305+
def paint_pareto(self):
306+
self.plotter.plot_pareto(self.first_criteria_values, self.second_criteria_values)
307+
308+
def save_image(self):
309+
if not os.path.isdir(self.path_for_saves):
310+
if self.path_for_saves == "":
311+
plt.savefig(self.file_name)
312+
else:
313+
os.mkdir(self.path_for_saves)
314+
plt.savefig(self.path_for_saves + "/" + self.file_name)
315+
else:
316+
plt.savefig(self.path_for_saves + "/" + self.file_name)
317+
plt.show()

0 commit comments

Comments
 (0)