# This file is part of qdpy.
#
# qdpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# qdpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
## @file
# @brief Evaluation callbacks, iteration summaries, and saved results.
"""TODO""" # TODO
__all__ = ["LoggerStat", "AlgorithmLogger", "TQDMAlgorithmLogger", "default_algorithm_logger"]
import os
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload, NamedTuple
import warnings
import numpy as np
import pandas as pd
import threading
import sys
from .base import *
from qdpy.utils import *
from qdpy.phenotype import *
from qdpy.base import *
from qdpy.base import _atomic_output_path
from qdpy.containers import *
from qdpy import tools
[docs]
class LoggerStat(NamedTuple):
"""Describe a named custom statistic.
With ``every_iteration=True``, the callable receives the optimiser.
Otherwise it receives the optimiser and the evaluated individual.
The returned value is stored in the corresponding table.
"""
name: str
fn: Callable
every_iteration: bool = True
[docs]
class AlgorithmLogger(Saveable):
"""Collect evaluation and iteration records through optimiser callbacks.
Evaluation records include the incumbent's raw objectives, archive
size, and duration. The objective columns are named ``max0``,
``max1``, and so on, including in minimising runs. Missing objective
values in mixed runs are represented by NaN.
Display an unavailable normalised QD score as ``N/A`` and store it
as ``nan`` in the iteration table so it can be read as a number.
Set ``save_period`` to write periodic iteration snapshots, or zero to
disable them. ``final_filename`` controls the final pickle snapshot.
``final_hdf_filename`` optionally writes evaluation and iteration
tables with the HDF5 extra.
A saved result contains the archive, metrics, and supplied config
where available. Continue a current experiment with an explicit
warm start when needed. Result logs do not capture all evaluator and
random generator state.
"""
algorithms: MutableSequence[QDAlgorithmLike]
iteration_filenames: Union[str, Callable]
final_filename: str
final_hdf_filename: Optional[str]
save_period: int
verbose: bool
log_base_path: str
config: Any
saved_dict: Mapping
_cols_names: MutableSequence[str] = ["alg_name", "iteration", "cont_size", "evals", "nb_updated", "avg", "std", "min", "max", "ft_min", "ft_max", "qd_score", "elapsed"]
_cols_size: MutableSequence[int]
_min_cols_size: int = 6
_first_iteration: bool
_current_iteration: int
_current_evaluation: int
_tabs_size: int = 6
#_cols_names_evals: Sequence[str] = ["alg_name", "iteration", "cont_size", "max", "elapsed"]
_evals_data: MutableMapping[str, MutableSequence[Any]]
_custom_stats: MutableSequence[LoggerStat]
_iterations_data: MutableMapping[str, MutableSequence[Any]]
_lock_evals_data: threading.Lock
_lock_iterations_data: threading.Lock
def __getstate__(self):
odict = self.__dict__.copy()
del odict['_lock_evals_data']
del odict['_lock_iterations_data']
return odict
def __setstate__(self, state):
self.__dict__.update(state)
self._lock_evals_data = threading.Lock()
self._lock_iterations_data = threading.Lock()
def __init__(self, algorithms: Union[QDAlgorithmLike, Sequence[QDAlgorithmLike]] = (),
iteration_filenames: Union[str, Callable] = "iteration-%i.p", final_filename: str = "final.p",
final_hdf_filename: Optional[str] = None,
save_period: int = 0, verbose: bool = True,
log_base_path: str = ".", config: Any = None,
saved_dict: Optional[Mapping] = None, tabs_size: int = 5,
stats: Sequence[LoggerStat] = ()):
self.iteration_filenames = iteration_filenames
self.final_filename = final_filename
self.final_hdf_filename = final_hdf_filename
self.save_period = save_period
self.verbose = verbose
self.algorithms = []
self.log_base_path = log_base_path
self.config = config
self.saved_dict = {} if saved_dict is None else saved_dict
self._tabs_size = tabs_size
self._first_iteration = False
self._current_iteration = 0
self._current_evaluation = 0
self._cols_names = list(self._cols_names)
self._cols_size = [len(x) for x in self._cols_names]
# Initialise dataframes
#self.evals = pd.DataFrame(index=np.arange(0, tot_budget), columns=self._cols_names_evals, dtype=object)
#self.evals = pd.DataFrame(index=np.arange(0, tot_budget), columns=self._cols_names_evals)
#self.evals = pd.DataFrame(columns=self._cols_names_evals)
#self.iterations = pd.DataFrame(columns=self._cols_names)
self._iterations_data = {k:[] for k in self._cols_names}
self._lock_iterations_data = threading.Lock()
#self._evals_data = {k:[] for k in self._cols_names_evals}
self._evals_data = {}
self._lock_evals_data = threading.Lock()
# Register new stats
self._custom_stats = []
self.register_stat(*stats)
# Set algorithms to be monitored
self.monitor(algorithms)
@property
def evals(self) -> pd.DataFrame:
"""The recorded evaluation statistics as a data frame."""
with self._lock_evals_data:
return pd.DataFrame(self._evals_data)
@property
def iterations(self) -> pd.DataFrame:
"""The recorded iteration statistics as a data frame."""
with self._lock_iterations_data:
return pd.DataFrame(self._iterations_data)
def __get_saved_state__(self) -> Mapping[str, Any]:
"""Return a dictionary containing the relevant information to save.
Only include information from `self.algorithms`, and evaluations and iterations DataFrames."""
if len(self.algorithms) == 1 and isinstance(self.algorithms[0], Saveable):
algos: Mapping[str, Any] = self.algorithms[0].__get_saved_state__()
else:
algos = {a.name: a for a in self.algorithms}
return {**algos, "evals": self.evals, "iterations": self.iterations, "config": self.config, **self.saved_dict}
def _output(self, *args):
print(*args)
def _gen_iteration_filename(self, iteration: Optional[int] = None) -> str:
"""Generate the filename of an iteration log file."""
if isinstance(self.iteration_filenames, str):
if iteration is None:
raise ValueError("`iteration` must be provided.")
return self.iteration_filenames % iteration
else:
return self.iteration_filenames()
def _stats_iteration(self, algo: QDAlgorithmLike, batch_elapsed: float) -> Sequence[Any]:
alg_name = algo.name
#iteration = algo.current_iter - 1
iteration = self._current_iteration
container = algo.container
cont_size = container.size_str()
evals = algo.nb_evaluations_in_iteration
nb_updated = algo.nb_updated_in_iteration
get_fitness = container.get_ind_fitness
fitness_values = np.array([get_fitness(ind).values for ind in container])
avg_values = np.mean(fitness_values, axis=0) if len(fitness_values) else np.nan
std_values = np.std(fitness_values, axis=0) if len(fitness_values) else np.nan
min_values = np.min(fitness_values, axis=0) if len(fitness_values) else np.nan
max_values = np.max(fitness_values, axis=0) if len(fitness_values) else np.nan
features_extrema = container.features_extrema
if features_extrema is not None:
ft_min_values = "[" + ",".join(f"{lower:.4f}" for lower, _ in features_extrema) + "]"
ft_max_values = "[" + ",".join(f"{upper:.4f}" for _, upper in features_extrema) + "]"
else:
features_domain = container.features_domain
feature_count = len(features_domain) if features_domain is not None else 0
ft_min_values = ft_max_values = "[" + ",".join(["NaN"] * feature_count) + "]"
qd_score = f"{container.qd_score(normalized=True):.2f}"
batch_elapsed_str = f"{batch_elapsed:.2f}"
# Compute custom stats
custom_stats_vals = [catch(s.fn, lambda e: None, algo) for s in self._custom_stats]
# Regroup all stats into formatted list of strings
with np.printoptions(precision=4, suppress=True):
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))
return res
def _init_cols(self, content: Sequence[Any]) -> None:
#assert(len(content) == len(self._cols_size))
cont2 = content[:len(self._cols_size)]
c_size: Sequence[int] = [len(f"{c}") for c in cont2]
self._cols_size = [max(a, b, self._min_cols_size) for a, b in zip(self._cols_size, c_size)]
def _vals_to_cols(self, content: Sequence[Any]) -> str:
#assert(len(content) == len(self._cols_size))
cont2 = content[:len(self._cols_size)]
str_c: MutableSequence[str] = []
for i, c in enumerate(cont2):
if self._cols_names[i] == "qd_score" and c == "nan":
c = "N/A"
str_c.append(("{0:<" + str(self._cols_size[i]) + "}").format(f"{c}"))
res: str = "\t".join(str_c)
return res.expandtabs(self._tabs_size)
def _vals_to_cols_title(self, content: Sequence[Any]) -> str:
return self._vals_to_cols(content)
def _str_to_col(self, s: str, length: int) -> str:
return ("{0:<" + str(length) + "}").format(s)
## @brief Publish a complete evaluation row under the table lock.
# @param algo Algorithm that had its evaluation reported.
# @param ind Evaluated candidate.
# @param added Reported archive update result.
# @param xattr Additional optimisation feedback metadata.
# @details Compute user statistics outside the lock. A failure leaves
# the preceding records available. Add NaN placeholders when a
# later record introduces another objective or statistic column.
def _tell(self, algo: QDAlgorithmLike, ind: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) -> None:
fitness = algo.container.best_fitness
values = fitness.values if fitness is not None else (np.nan,)
row = {
"alg_name": algo.name,
"iteration": self._current_iteration,
"cont_size": algo.container.size,
**{f"max{i}": value for i, value in enumerate(values)},
"elapsed": ind.elapsed,
}
row.update({s.name: s.fn(algo, ind) for s in self._custom_stats if not s.every_iteration})
with self._lock_evals_data:
for name, column in self._evals_data.items():
column.append(row.pop(name, np.nan))
for name, value in row.items():
self._evals_data[name] = [np.nan] * self._current_evaluation + [value]
self._current_evaluation += 1
def _iteration(self, algo: QDAlgorithmLike, batch_elapsed: float) -> None:
stats: Sequence[Any] = self._stats_iteration(algo, batch_elapsed)
if self.verbose:
if self._first_iteration:
self._first_iteration = False
self._init_cols(stats)
self._output(self._vals_to_cols_title(self._cols_names))
self._output(self._vals_to_cols(stats))
#finished_iter_nb: int = algo.current_iter - 1
finished_iter_nb: int = self._current_iteration
# Update iteration infos
with self._lock_iterations_data:
for i, name in enumerate(self._cols_names):
self._iterations_data[name].append(stats[i] if i < len(stats) else np.nan)
if self.save_period != 0 and finished_iter_nb % self.save_period == 0:
if not (isinstance(self.iteration_filenames, str) and len(self.iteration_filenames) == 0):
self.save(os.path.join(self.log_base_path, self._gen_iteration_filename(finished_iter_nb)))
# Update current iteration nb
self._current_iteration += 1
def _started_optimisation(self, algo: QDAlgorithmLike) -> None:
self._first_iteration = True
def _finished_optimisation(self, algo: QDAlgorithmLike, optimisation_elapsed: float) -> None:
if self.verbose:
self._output(f"Finished optimisation using algorithm '{algo.name}'. Total elapsed: {optimisation_elapsed}.")
if self.final_filename:
self.save(os.path.join(self.log_base_path, self.final_filename))
if self.final_hdf_filename:
with _atomic_output_path(os.path.join(self.log_base_path, self.final_hdf_filename)) as temporary:
self.iterations.to_hdf(temporary, key="iterations", mode="w")
self.evals.to_hdf(temporary, key="evals")
[docs]
def monitor(self, algorithms: Union[QDAlgorithmLike, Sequence[QDAlgorithmLike]]) -> None:
"""Attach evaluation, iteration, start, and finish callbacks to the specified optimisers."""
if isinstance(algorithms, QDAlgorithmLike):
algorithms = [algorithms]
for a in algorithms:
a.add_callback("tell", self._tell)
a.add_callback("iteration", self._iteration)
a.add_callback("started_optimisation", self._started_optimisation)
a.add_callback("finished_optimisation", self._finished_optimisation)
self.algorithms.append(a)
[docs]
def register_stat(self, *stat: LoggerStat) -> None:
#if len(self.algorithms) > 0:
# raise RuntimeError("`register_stat` cannot be called while the logger is already monitoring one algorithm.")
"""Register one or more LoggerStat entries on this logger."""
for s in stat:
self._custom_stats.append(s)
if s.every_iteration:
with self._lock_iterations_data:
self._cols_names.append(s.name)
self._iterations_data[s.name] = [np.nan] * len(self._iterations_data["iteration"])
self._cols_size.append(len(s.name))
default_algorithm_logger = AlgorithmLogger(iteration_filenames = "", final_filename = "", verbose = True)
# Colorama is a python package to easily produce colored terminal outputs
try:
import colorama
_IMPORTED_COLORAMA = True
colorama.init()
except Exception:
_IMPORTED_COLORAMA = False
try:
import tqdm
_IMPORTED_TQDM = True
import tqdm.contrib
class TQDMAlgorithmLogger(AlgorithmLogger):
"""Collect AlgorithmLogger records and display evaluation progress with the progress extra."""
_tqdm_pbar: Optional[Any]
_redirect_outputs: bool
def __getstate__(self):
entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)}
return entries
def __init__(self, *args, redirect_outputs: bool = False, **kwargs):
super().__init__(*args, **kwargs)
self._tqdm_pbar = None
self._redirect_outputs = redirect_outputs
self._orig_out_err = sys.stdout, sys.stderr
def _output(self, *args):
if self._tqdm_pbar is not None:
self._tqdm_pbar.write("".join(args))
def _started_optimisation(self, algo: QDAlgorithmLike) -> None:
super()._started_optimisation(algo)
if self._tqdm_pbar is not None:
self._tqdm_pbar.close()
self._orig_out_err = sys.stdout, sys.stderr
sys.stdout, sys.stderr = map(tqdm.contrib.DummyTqdmFile, self._orig_out_err)
self._tqdm_pbar = tqdm.tqdm(total=algo.budget, file=self._orig_out_err[0], unit="eval", leave=False)
def _finished_optimisation(self, algo: QDAlgorithmLike, optimisation_elapsed: float) -> None:
super()._finished_optimisation(algo, optimisation_elapsed)
if self._tqdm_pbar is not None:
self._tqdm_pbar.close()
self._tqdm_pbar = None
sys.stdout, sys.stderr = self._orig_out_err
def _tell(self, algo: QDAlgorithmLike, ind: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) -> None:
super()._tell(algo, ind, added, xattr)
if self._tqdm_pbar is not None:
self._tqdm_pbar.set_postfix(iteration=self._current_iteration)
self._tqdm_pbar.update(1)
def _vals_to_cols_title(self, content: Sequence[Any]) -> str:
if _IMPORTED_COLORAMA:
#assert(len(content) == len(self._cols_size))
cont2 = content[:len(self._cols_size)]
prefix = "" + colorama.Style.BRIGHT + colorama.Back.RED
suffix = "" + colorama.Style.RESET_ALL
str_c: MutableSequence[str] = []
for i, c in enumerate(cont2):
str_c.append(("{0:<" + str(self._cols_size[i]) + "}").format(f"{c}"))
res: str = prefix + "\t".join(str_c) + suffix
return res.expandtabs(self._tabs_size)
else:
return super()._vals_to_cols_title(content)
except ImportError:
class TQDMAlgorithmLogger(AlgorithmLogger): # type: ignore
def __init__(self, *args, **kwargs):
warnings.warn(f"`TQDMAlgorithmLogger` class needs the 'tqdm' package to be installed and importable. Using the base `AlgorithmLogger` instead.")
super().__init__(*args, **kwargs)
#raise NotImplementedError("`TQDMAlgorithmLogger` needs the 'tqdm' package to be installed and importable.")
# MODELINE "{{{1
# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
# vim:foldmethod=marker