/
observer.py
211 lines (163 loc) · 7.67 KB
/
observer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import logging
import os
from pathlib import Path
from typing import List, TypeVar
import numpy as np
from tqdm import tqdm
from jmetal.core.observer import Observer
from jmetal.core.problem import DynamicProblem
from jmetal.core.quality_indicator import InvertedGenerationalDistance
from jmetal.lab.visualization import Plot, StreamingPlot
from jmetal.util.solution import print_function_values_to_file
S = TypeVar("S")
LOGGER = logging.getLogger("jmetal")
"""
.. module:: observer
:platform: Unix, Windows
:synopsis: Implementation of algorithm's observers.
.. moduleauthor:: Antonio J. Nebro <antonio@lcc.uma.es>
"""
class ProgressBarObserver(Observer):
def __init__(self, max: int) -> None:
"""Show a smart progress meter with the number of evaluations and computing time.
:param max: Number of expected iterations.
"""
self.progress_bar = None
self.progress = 0
self._max = max
def update(self, *args, **kwargs):
if not self.progress_bar:
self.progress_bar = tqdm(total=self._max, ascii=True, desc="Progress")
evaluations = kwargs["EVALUATIONS"]
self.progress_bar.update(evaluations - self.progress)
self.progress = evaluations
if self.progress >= self._max:
self.progress_bar.close()
class BasicObserver(Observer):
def __init__(self, frequency: int = 1) -> None:
"""Show the number of evaluations, the best fitness and the computing time.
:param frequency: Display frequency."""
self.display_frequency = frequency
def update(self, *args, **kwargs):
computing_time = kwargs["COMPUTING_TIME"]
evaluations = kwargs["EVALUATIONS"]
solutions = kwargs["SOLUTIONS"]
if (evaluations % self.display_frequency) == 0 and solutions:
if type(solutions) == list:
fitness = solutions[0].objectives
else:
fitness = solutions.objectives
LOGGER.info(
"Evaluations: {} \n Best fitness: {} \n Computing time: {}".format(evaluations, fitness, computing_time)
)
class PrintObjectivesObserver(Observer):
def __init__(self, frequency: int = 1) -> None:
"""Show the number of evaluations, best fitness and computing time.
:param frequency: Display frequency."""
self.display_frequency = frequency
def update(self, *args, **kwargs):
evaluations = kwargs["EVALUATIONS"]
solutions = kwargs["SOLUTIONS"]
if (evaluations % self.display_frequency) == 0 and solutions:
if type(solutions) == list:
fitness = solutions[0].objectives
else:
fitness = solutions.objectives
LOGGER.info("Evaluations: {}. fitness: {}".format(evaluations, fitness))
class WriteFrontToFileObserver(Observer):
def __init__(self, output_directory: str) -> None:
"""Write function values of the front into files.
:param output_directory: Output directory. Each front will be saved on a file `FUN.x`."""
self.counter = 0
self.directory = output_directory
if Path(self.directory).is_dir():
LOGGER.warning("Directory {} exists. Removing contents.".format(self.directory))
for file in os.listdir(self.directory):
os.remove("{0}/{1}".format(self.directory, file))
else:
LOGGER.warning("Directory {} does not exist. Creating it.".format(self.directory))
Path(self.directory).mkdir(parents=True)
def update(self, *args, **kwargs):
problem = kwargs["PROBLEM"]
solutions = kwargs["SOLUTIONS"]
if solutions:
if isinstance(problem, DynamicProblem):
termination_criterion_is_met = kwargs.get("TERMINATION_CRITERIA_IS_MET", None)
if termination_criterion_is_met:
print_function_values_to_file(solutions, "{}/FUN.{}".format(self.directory, self.counter))
self.counter += 1
else:
print_function_values_to_file(solutions, "{}/FUN.{}".format(self.directory, self.counter))
self.counter += 1
class PlotFrontToFileObserver(Observer):
def __init__(self, output_directory: str, step: int = 100, **kwargs) -> None:
"""Plot and save Pareto front approximations into files.
:param output_directory: Output directory.
"""
self.directory = output_directory
self.plot_front = Plot(title="Pareto front approximation", **kwargs)
self.last_front = []
self.fronts = []
self.counter = 0
self.step = step
if Path(self.directory).is_dir():
LOGGER.warning("Directory {} exists. Removing contents.".format(self.directory))
for file in os.listdir(self.directory):
os.remove("{0}/{1}".format(self.directory, file))
else:
LOGGER.warning("Directory {} does not exist. Creating it.".format(self.directory))
Path(self.directory).mkdir(parents=True)
def update(self, *args, **kwargs):
problem = kwargs["PROBLEM"]
solutions = kwargs["SOLUTIONS"]
evaluations = kwargs["EVALUATIONS"]
if solutions:
if (evaluations % self.step) == 0:
if isinstance(problem, DynamicProblem):
termination_criterion_is_met = kwargs.get("TERMINATION_CRITERIA_IS_MET", None)
if termination_criterion_is_met:
if self.counter > 0:
igd = InvertedGenerationalDistance(np.array([s.objectives for s in self.last_front]))
igd_value = igd.compute(np.array([s.objectives for s in solutions]))
else:
igd_value = 1
if igd_value > 0.005:
self.fronts += solutions
self.plot_front.plot(
[self.fronts],
label=problem.get_name(),
filename=f"{self.directory}/front-{evaluations}",
)
self.counter += 1
self.last_front = solutions
else:
self.plot_front.plot(
[solutions],
label=f"{evaluations} evaluations",
filename=f"{self.directory}/front-{evaluations}",
)
self.counter += 1
class VisualizerObserver(Observer):
def __init__(
self, reference_front: List[S] = None, reference_point: list = None, display_frequency: int = 1
) -> None:
self.figure = None
self.display_frequency = display_frequency
self.reference_point = reference_point
self.reference_front = reference_front
def update(self, *args, **kwargs):
evaluations = kwargs["EVALUATIONS"]
solutions = kwargs["SOLUTIONS"]
if solutions:
if self.figure is None:
self.figure = StreamingPlot(reference_point=self.reference_point, reference_front=self.reference_front)
self.figure.plot(solutions)
if (evaluations % self.display_frequency) == 0:
# check if reference point has changed
reference_point = kwargs.get("REFERENCE_POINT", None)
if reference_point:
self.reference_point = reference_point
self.figure.update(solutions, reference_point)
else:
self.figure.update(solutions)
self.figure.ax.set_title("Eval: {}".format(evaluations), fontsize=13)