25from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload, NamedTuple
55 """Collect evaluation and iteration records through optimiser callbacks.
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.
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.
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.
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.
75 algorithms: MutableSequence[QDAlgorithmLike]
76 iteration_filenames: Union[str, Callable]
78 final_hdf_filename: Optional[str]
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
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
101 def __getstate__(self):
102 odict = self.__dict__.copy()
103 del odict[
'_lock_evals_data']
104 del odict[
'_lock_iterations_data']
107 def __setstate__(self, state):
108 self.__dict__.update(state)
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] = ()):
128 self.
saved_dict = {}
if saved_dict
is None else saved_dict
153 def evals(self) -> pd.DataFrame:
154 """The recorded evaluation statistics as a data frame."""
159 def iterations(self) -> pd.DataFrame:
160 """The recorded iteration statistics as a data frame."""
166 """Return a dictionary containing the relevant information to save.
167 Only include information from `self.algorithms`, and evaluations and iterations DataFrames."""
175 def _output(self, *args):
179 """Generate the filename of an iteration log file."""
181 if iteration
is None:
182 raise ValueError(
"`iteration` must be provided.")
188 def _stats_iteration(self, algo: QDAlgorithmLike, batch_elapsed: float) -> Sequence[Any]:
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) +
"]"
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}"
214 custom_stats_vals = [catch(s.fn,
lambda e:
None, algo)
for s
in self.
_custom_stats]
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))
222 def _init_cols(self, content: Sequence[Any]) ->
None:
225 c_size: Sequence[int] = [len(f
"{c}")
for c
in cont2]
229 def _vals_to_cols(self, content: Sequence[Any]) -> str:
232 str_c: MutableSequence[str] = []
233 for i, c
in enumerate(cont2):
234 if self.
_cols_names[i] ==
"qd_score" and c ==
"nan":
236 str_c.append((
"{0:<" + str(self.
_cols_size[i]) +
"}").format(f
"{c}"))
237 res: str =
"\t".join(str_c)
240 def _vals_to_cols_title(self, content: Sequence[Any]) -> str:
243 def _str_to_col(self, s: str, length: int) -> str:
244 return (
"{0:<" + str(length) +
"}").format(s)
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,)
259 "alg_name": algo.name,
261 "cont_size": algo.container.size,
262 **{f
"max{i}": value
for i, value
in enumerate(values)},
263 "elapsed": ind.elapsed,
265 row.update({s.name: s.fn(algo, ind)
for s
in self.
_custom_stats if not s.every_iteration})
268 column.append(row.pop(name, np.nan))
269 for name, value
in row.items():
274 def _iteration(self, algo: QDAlgorithmLike, batch_elapsed: float) ->
None:
294 def _started_optimisation(self, algo: QDAlgorithmLike) ->
None:
297 def _finished_optimisation(self, algo: QDAlgorithmLike, optimisation_elapsed: float) ->
None:
299 self.
_output(f
"Finished optimisation using algorithm '{algo.name}'. Total elapsed: {optimisation_elapsed}.")
304 self.
iterations.to_hdf(temporary, key=
"iterations", mode=
"w")
305 self.
evals.to_hdf(temporary, key=
"evals")
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]
312 a.add_callback(
"tell", self.
_tell)
322 """Register one or more LoggerStat entries on this logger."""
325 if s.every_iteration:
350 """Collect AlgorithmLogger records and display evaluation progress with the progress extra."""
351 _tqdm_pbar: Optional[Any]
352 _redirect_outputs: bool
354 def __getstate__(self):
355 entries = {k:v
for k,v
in inspect.getmembers(self)
if not k.startswith(
'_')
and not inspect.ismethod(v)}
358 def __init__(self, *args, redirect_outputs: bool =
False, **kwargs):
359 super().__init__(*args, **kwargs)
364 def _output(self, *args):
368 def _started_optimisation(self, algo: QDAlgorithmLike) ->
None:
369 super()._started_optimisation(algo)
373 sys.stdout, sys.stderr = map(tqdm.contrib.DummyTqdmFile, self.
_orig_out_err)
376 def _finished_optimisation(self, algo: QDAlgorithmLike, optimisation_elapsed: float) ->
None:
377 super()._finished_optimisation(algo, optimisation_elapsed)
383 def _tell(self, algo: QDAlgorithmLike, ind: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) ->
None:
384 super()._tell(algo, ind, added, xattr)
389 def _vals_to_cols_title(self, content: Sequence[Any]) -> str:
390 if _IMPORTED_COLORAMA:
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
401 return super()._vals_to_cols_title(content)