QDpy
Loading...
Searching...
No Matches
logging.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""TODO""" # TODO
20
21__all__ = ["LoggerStat", "AlgorithmLogger", "TQDMAlgorithmLogger", "default_algorithm_logger"]
22
23
24import os
25from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload, NamedTuple
26import warnings
27import numpy as np
28import pandas as pd
29import threading
30import sys
31
32
33from .base import *
34from qdpy.utils import *
35from qdpy.phenotype import *
36from qdpy.base import *
37from qdpy.base import _atomic_output_path
38from qdpy.containers import *
39from qdpy import tools
40
41
42class LoggerStat(NamedTuple):
43 """Describe a named custom statistic.
44
45 With ``every_iteration=True``, the callable receives the optimiser.
46 Otherwise it receives the optimiser and the evaluated individual.
47 The returned value is stored in the corresponding table.
48 """
49 name: str
50 fn: Callable
51 every_iteration: bool = True
52
53
55 """Collect evaluation and iteration records through optimiser callbacks.
56
57 Evaluation records include the incumbent's raw objectives, archive
58 size, and duration. The objective columns are named ``max0``,
59 ``max1``, and so on, including in minimising runs. Missing objective
60 values in mixed runs are represented by NaN.
61
62 Display an unavailable normalised QD score as ``N/A`` and store it
63 as ``nan`` in the iteration table so it can be read as a number.
64
65 Set ``save_period`` to write periodic iteration snapshots, or zero to
66 disable them. ``final_filename`` controls the final pickle snapshot.
67 ``final_hdf_filename`` optionally writes evaluation and iteration
68 tables with the HDF5 extra.
69
70 A saved result contains the archive, metrics, and supplied config
71 where available. Continue a current experiment with an explicit
72 warm start when needed. Result logs do not capture all evaluator and
73 random generator state.
74 """
75 algorithms: MutableSequence[QDAlgorithmLike]
76 iteration_filenames: Union[str, Callable]
77 final_filename: str
78 final_hdf_filename: Optional[str]
79 save_period: int
80 verbose: bool
81 log_base_path: str
82 config: Any
83 saved_dict: Mapping
84
85 _cols_names: MutableSequence[str] = ["alg_name", "iteration", "cont_size", "evals", "nb_updated", "avg", "std", "min", "max", "ft_min", "ft_max", "qd_score", "elapsed"]
86 _cols_size: MutableSequence[int]
87 _min_cols_size: int = 6
88 _first_iteration: bool
89 _current_iteration: int
90 _current_evaluation: int
91 _tabs_size: int = 6
92
93 #_cols_names_evals: Sequence[str] = ["alg_name", "iteration", "cont_size", "max", "elapsed"]
94 _evals_data: MutableMapping[str, MutableSequence[Any]]
95 _custom_stats: MutableSequence[LoggerStat]
96 _iterations_data: MutableMapping[str, MutableSequence[Any]]
97 _lock_evals_data: threading.Lock
98 _lock_iterations_data: threading.Lock
99
100
101 def __getstate__(self):
102 odict = self.__dict__.copy()
103 del odict['_lock_evals_data']
104 del odict['_lock_iterations_data']
105 return odict
106
107 def __setstate__(self, state):
108 self.__dict__.update(state)
109 self._lock_evals_data = threading.Lock()
110 self._lock_iterations_data = threading.Lock()
111
112
113 def __init__(self, algorithms: Union[QDAlgorithmLike, Sequence[QDAlgorithmLike]] = (),
114 iteration_filenames: Union[str, Callable] = "iteration-%i.p", final_filename: str = "final.p",
115 final_hdf_filename: Optional[str] = None,
116 save_period: int = 0, verbose: bool = True,
117 log_base_path: str = ".", config: Any = None,
118 saved_dict: Optional[Mapping] = None, tabs_size: int = 5,
119 stats: Sequence[LoggerStat] = ()):
120 self.iteration_filenames = iteration_filenames
121 self.final_filename = final_filename
122 self.final_hdf_filename = final_hdf_filename
123 self.save_period = save_period
124 self.verbose = verbose
125 self.algorithms = []
126 self.log_base_path = log_base_path
127 self.config = config
128 self.saved_dict = {} if saved_dict is None else saved_dict
129 self._tabs_size = tabs_size
130 self._first_iteration = False
131 self._current_iteration = 0
132 self._current_evaluation = 0
133 self._cols_names = list(self._cols_names)
134 self._cols_size = [len(x) for x in self._cols_names]
135 # Initialise dataframes
136 #self.evals = pd.DataFrame(index=np.arange(0, tot_budget), columns=self._cols_names_evals, dtype=object)
137 #self.evals = pd.DataFrame(index=np.arange(0, tot_budget), columns=self._cols_names_evals)
138 #self.evals = pd.DataFrame(columns=self._cols_names_evals)
139 #self.iterations = pd.DataFrame(columns=self._cols_names)
140 self._iterations_data = {k:[] for k in self._cols_names}
141 self._lock_iterations_data = threading.Lock()
142 #self._evals_data = {k:[] for k in self._cols_names_evals}
143 self._evals_data = {}
144 self._lock_evals_data = threading.Lock()
145 # Register new stats
146 self._custom_stats = []
147 self.register_stat(*stats)
148 # Set algorithms to be monitored
149 self.monitor(algorithms)
150
151
152 @property
153 def evals(self) -> pd.DataFrame:
154 """The recorded evaluation statistics as a data frame."""
155 with self._lock_evals_data:
156 return pd.DataFrame(self._evals_data)
157
158 @property
159 def iterations(self) -> pd.DataFrame:
160 """The recorded iteration statistics as a data frame."""
161 with self._lock_iterations_data:
162 return pd.DataFrame(self._iterations_data)
163
164
165 def __get_saved_state__(self) -> Mapping[str, Any]:
166 """Return a dictionary containing the relevant information to save.
167 Only include information from `self.algorithms`, and evaluations and iterations DataFrames."""
168 if len(self.algorithms) == 1 and isinstance(self.algorithms[0], Saveable):
169 algos: Mapping[str, Any] = self.algorithms[0].__get_saved_state__()
170 else:
171 algos = {a.name: a for a in self.algorithms}
172 return {**algos, "evals": self.evals, "iterations": self.iterations, "config": self.config, **self.saved_dict}
173
174
175 def _output(self, *args):
176 print(*args)
177
178 def _gen_iteration_filename(self, iteration: Optional[int] = None) -> str:
179 """Generate the filename of an iteration log file."""
180 if isinstance(self.iteration_filenames, str):
181 if iteration is None:
182 raise ValueError("`iteration` must be provided.")
183 return self.iteration_filenames % iteration
184 else:
185 return self.iteration_filenames()
186
187
188 def _stats_iteration(self, algo: QDAlgorithmLike, batch_elapsed: float) -> Sequence[Any]:
189 alg_name = algo.name
190 #iteration = algo.current_iter - 1
191 iteration = self._current_iteration
192 container = algo.container
193 cont_size = container.size_str()
194 evals = algo.nb_evaluations_in_iteration
195 nb_updated = algo.nb_updated_in_iteration
196 get_fitness = container.get_ind_fitness
197 fitness_values = np.array([get_fitness(ind).values for ind in container])
198 avg_values = np.mean(fitness_values, axis=0) if len(fitness_values) else np.nan
199 std_values = np.std(fitness_values, axis=0) if len(fitness_values) else np.nan
200 min_values = np.min(fitness_values, axis=0) if len(fitness_values) else np.nan
201 max_values = np.max(fitness_values, axis=0) if len(fitness_values) else np.nan
202 features_extrema = container.features_extrema
203 if features_extrema is not None:
204 ft_min_values = "[" + ",".join(f"{lower:.4f}" for lower, _ in features_extrema) + "]"
205 ft_max_values = "[" + ",".join(f"{upper:.4f}" for _, upper in features_extrema) + "]"
206 else:
207 features_domain = container.features_domain
208 feature_count = len(features_domain) if features_domain is not None else 0
209 ft_min_values = ft_max_values = "[" + ",".join(["NaN"] * feature_count) + "]"
210 qd_score = f"{container.qd_score(normalized=True):.2f}"
211 batch_elapsed_str = f"{batch_elapsed:.2f}"
212
213 # Compute custom stats
214 custom_stats_vals = [catch(s.fn, lambda e: None, algo) for s in self._custom_stats]
215
216 # Regroup all stats into formatted list of strings
217 with np.printoptions(precision=4, suppress=True):
218 res = list(map(str, [alg_name, iteration, cont_size, evals, nb_updated, avg_values, std_values, min_values, max_values, ft_min_values, ft_max_values, qd_score, batch_elapsed_str] + custom_stats_vals))
219 return res
220
221
222 def _init_cols(self, content: Sequence[Any]) -> None:
223 #assert(len(content) == len(self._cols_size))
224 cont2 = content[:len(self._cols_size)]
225 c_size: Sequence[int] = [len(f"{c}") for c in cont2]
226 self._cols_size = [max(a, b, self._min_cols_size) for a, b in zip(self._cols_size, c_size)]
227
228
229 def _vals_to_cols(self, content: Sequence[Any]) -> str:
230 #assert(len(content) == len(self._cols_size))
231 cont2 = content[:len(self._cols_size)]
232 str_c: MutableSequence[str] = []
233 for i, c in enumerate(cont2):
234 if self._cols_names[i] == "qd_score" and c == "nan":
235 c = "N/A"
236 str_c.append(("{0:<" + str(self._cols_size[i]) + "}").format(f"{c}"))
237 res: str = "\t".join(str_c)
238 return res.expandtabs(self._tabs_size)
239
240 def _vals_to_cols_title(self, content: Sequence[Any]) -> str:
241 return self._vals_to_cols(content)
242
243 def _str_to_col(self, s: str, length: int) -> str:
244 return ("{0:<" + str(length) + "}").format(s)
245
246
247
255 def _tell(self, algo: QDAlgorithmLike, ind: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) -> None:
256 fitness = algo.container.best_fitness
257 values = fitness.values if fitness is not None else (np.nan,)
258 row = {
259 "alg_name": algo.name,
260 "iteration": self._current_iteration,
261 "cont_size": algo.container.size,
262 **{f"max{i}": value for i, value in enumerate(values)},
263 "elapsed": ind.elapsed,
264 }
265 row.update({s.name: s.fn(algo, ind) for s in self._custom_stats if not s.every_iteration})
266 with self._lock_evals_data:
267 for name, column in self._evals_data.items():
268 column.append(row.pop(name, np.nan))
269 for name, value in row.items():
270 self._evals_data[name] = [np.nan] * self._current_evaluation + [value]
271 self._current_evaluation += 1
272
273
274 def _iteration(self, algo: QDAlgorithmLike, batch_elapsed: float) -> None:
275 stats: Sequence[Any] = self._stats_iteration(algo, batch_elapsed)
276 if self.verbose:
277 if self._first_iteration:
278 self._first_iteration = False
279 self._init_cols(stats)
281 self._output(self._vals_to_cols(stats))
282 #finished_iter_nb: int = algo.current_iter - 1
283 finished_iter_nb: int = self._current_iteration
284 # Update iteration infos
285 with self._lock_iterations_data:
286 for i, name in enumerate(self._cols_names):
287 self._iterations_data[name].append(stats[i] if i < len(stats) else np.nan)
288 if self.save_period != 0 and finished_iter_nb % self.save_period == 0:
289 if not (isinstance(self.iteration_filenames, str) and len(self.iteration_filenames) == 0):
290 self.save(os.path.join(self.log_base_path, self._gen_iteration_filename(finished_iter_nb)))
291 # Update current iteration nb
292 self._current_iteration += 1
293
294 def _started_optimisation(self, algo: QDAlgorithmLike) -> None:
295 self._first_iteration = True
296
297 def _finished_optimisation(self, algo: QDAlgorithmLike, optimisation_elapsed: float) -> None:
298 if self.verbose:
299 self._output(f"Finished optimisation using algorithm '{algo.name}'. Total elapsed: {optimisation_elapsed}.")
300 if self.final_filename:
301 self.save(os.path.join(self.log_base_path, self.final_filename))
302 if self.final_hdf_filename:
303 with _atomic_output_path(os.path.join(self.log_base_path, self.final_hdf_filename)) as temporary:
304 self.iterations.to_hdf(temporary, key="iterations", mode="w")
305 self.evals.to_hdf(temporary, key="evals")
306
307 def monitor(self, algorithms: Union[QDAlgorithmLike, Sequence[QDAlgorithmLike]]) -> None:
308 """Attach evaluation, iteration, start, and finish callbacks to the specified optimisers."""
309 if isinstance(algorithms, QDAlgorithmLike):
310 algorithms = [algorithms]
311 for a in algorithms:
312 a.add_callback("tell", self._tell)
313 a.add_callback("iteration", self._iteration)
314 a.add_callback("started_optimisation", self._started_optimisation)
315 a.add_callback("finished_optimisation", self._finished_optimisation)
316 self.algorithms.append(a)
317
318
319 def register_stat(self, *stat: LoggerStat) -> None:
320 #if len(self.algorithms) > 0:
321 # raise RuntimeError("`register_stat` cannot be called while the logger is already monitoring one algorithm.")
322 """Register one or more LoggerStat entries on this logger."""
323 for s in stat:
324 self._custom_stats.append(s)
325 if s.every_iteration:
326 with self._lock_iterations_data:
327 self._cols_names.append(s.name)
328 self._iterations_data[s.name] = [np.nan] * len(self._iterations_data["iteration"])
329 self._cols_size.append(len(s.name))
330
331
332default_algorithm_logger = AlgorithmLogger(iteration_filenames = "", final_filename = "", verbose = True)
333
334
335# Colorama is a python package to easily produce colored terminal outputs
336try:
337 import colorama
338 _IMPORTED_COLORAMA = True
339 colorama.init()
340except Exception:
341 _IMPORTED_COLORAMA = False
342
343
344try:
345 import tqdm
346 _IMPORTED_TQDM = True
347 import tqdm.contrib
348
350 """Collect AlgorithmLogger records and display evaluation progress with the progress extra."""
351 _tqdm_pbar: Optional[Any]
352 _redirect_outputs: bool
353
354 def __getstate__(self):
355 entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)}
356 return entries
357
358 def __init__(self, *args, redirect_outputs: bool = False, **kwargs):
359 super().__init__(*args, **kwargs)
360 self._tqdm_pbar = None
361 self._redirect_outputs = redirect_outputs
362 self._orig_out_err = sys.stdout, sys.stderr
363
364 def _output(self, *args):
365 if self._tqdm_pbar is not None:
366 self._tqdm_pbar.write("".join(args))
367
368 def _started_optimisation(self, algo: QDAlgorithmLike) -> None:
369 super()._started_optimisation(algo)
370 if self._tqdm_pbar is not None:
371 self._tqdm_pbar.close()
372 self._orig_out_err = sys.stdout, sys.stderr
373 sys.stdout, sys.stderr = map(tqdm.contrib.DummyTqdmFile, self._orig_out_err)
374 self._tqdm_pbar = tqdm.tqdm(total=algo.budget, file=self._orig_out_err[0], unit="eval", leave=False)
375
376 def _finished_optimisation(self, algo: QDAlgorithmLike, optimisation_elapsed: float) -> None:
377 super()._finished_optimisation(algo, optimisation_elapsed)
378 if self._tqdm_pbar is not None:
379 self._tqdm_pbar.close()
380 self._tqdm_pbar = None
381 sys.stdout, sys.stderr = self._orig_out_err
382
383 def _tell(self, algo: QDAlgorithmLike, ind: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) -> None:
384 super()._tell(algo, ind, added, xattr)
385 if self._tqdm_pbar is not None:
386 self._tqdm_pbar.set_postfix(iteration=self._current_iteration)
387 self._tqdm_pbar.update(1)
388
389 def _vals_to_cols_title(self, content: Sequence[Any]) -> str:
390 if _IMPORTED_COLORAMA:
391 #assert(len(content) == len(self._cols_size))
392 cont2 = content[:len(self._cols_size)]
393 prefix = "" + colorama.Style.BRIGHT + colorama.Back.RED
394 suffix = "" + colorama.Style.RESET_ALL
395 str_c: MutableSequence[str] = []
396 for i, c in enumerate(cont2):
397 str_c.append(("{0:<" + str(self._cols_size[i]) + "}").format(f"{c}"))
398 res: str = prefix + "\t".join(str_c) + suffix
399 return res.expandtabs(self._tabs_size)
400 else:
401 return super()._vals_to_cols_title(content)
402
403except ImportError:
404 class TQDMAlgorithmLogger(AlgorithmLogger): # type: ignore
405 def __init__(self, *args, **kwargs):
406 warnings.warn(f"`TQDMAlgorithmLogger` class needs the 'tqdm' package to be installed and importable. Using the base `AlgorithmLogger` instead.")
407 super().__init__(*args, **kwargs)
408 #raise NotImplementedError("`TQDMAlgorithmLogger` needs the 'tqdm' package to be installed and importable.")
409
410
411# MODELINE "{{{1
412# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
413# vim:foldmethod=marker
str _vals_to_cols_title(self, Sequence[Any] content)
Definition logging.py:240
Sequence[Any] _stats_iteration(self, QDAlgorithmLike algo, float batch_elapsed)
Definition logging.py:188
Mapping[str, Any] __get_saved_state__(self)
Definition logging.py:165
str _gen_iteration_filename(self, Optional[int] iteration=None)
Definition logging.py:178
None monitor(self, Union[QDAlgorithmLike, Sequence[QDAlgorithmLike]] algorithms)
Definition logging.py:307
None register_stat(self, *LoggerStat stat)
Definition logging.py:319
None _init_cols(self, Sequence[Any] content)
Definition logging.py:222
str _vals_to_cols(self, Sequence[Any] content)
Definition logging.py:229
None save(self, str output_path, str output_type="pickle")
Definition base.py:527