Repository navigation
Replace custom colour implementation, add docs for logger.py, util.py
#435
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,82 +1,155 @@ | ||
| """Contains classes and functions for logging.""" | ||
| from __future__ import print_function | ||
| import os | ||
| import json | ||
| import warnings | ||
| from pathlib import Path | ||
| from .observer import _Tracker | ||
| from .event import Events | ||
| from .util import Colours | ||
| from colorama import Fore, just_fix_windows_console | ||
|
|
||
| just_fix_windows_console() | ||
|
|
||
| def _get_default_logger(verbose, is_constrained): | ||
| """ | ||
| Return the default logger. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| verbose : int | ||
| Verbosity level of the logger. | ||
|
|
||
| is_constrained : bool | ||
| Whether the underlying optimizer uses constraints (this requires | ||
| an additional column in the output). | ||
|
|
||
| Returns | ||
| ------- | ||
| ScreenLogger | ||
| The default logger. | ||
|
|
||
| """ | ||
| return ScreenLogger(verbose=verbose, is_constrained=is_constrained) | ||
|
|
||
|
|
||
| class ScreenLogger(_Tracker): | ||
| """Logger that outputs text, e.g. to log to a terminal. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| verbose : int | ||
| Verbosity level of the logger. | ||
|
|
||
| is_constrained : bool | ||
| Whether the logger is associated with a constrained optimization | ||
| instance. | ||
| """ | ||
|
|
||
| _default_cell_size = 9 | ||
| _default_precision = 4 | ||
|
|
||
| def __init__(self, verbose=2, is_constrained=False): | ||
| self._verbose = verbose | ||
| self._is_constrained = is_constrained | ||
| self._header_length = None | ||
| super(ScreenLogger, self).__init__() | ||
| super().__init__() | ||
|
|
||
| @property | ||
| def verbose(self): | ||
| """Return the verbosity level.""" | ||
| return self._verbose | ||
|
|
||
| @verbose.setter | ||
| def verbose(self, v): | ||
| """Set the verbosity level. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| v : int | ||
| New verbosity level of the logger. | ||
| """ | ||
| self._verbose = v | ||
|
|
||
| @property | ||
| def is_constrained(self): | ||
| """Return whether the logger is constrained.""" | ||
| return self._is_constrained | ||
|
|
||
| def _format_number(self, x): | ||
| """Format a number. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| x : number | ||
|
|
||
|
|
||
| Returns | ||
| ------- | ||
| A stringified, formatted version of `x`. | ||
| """ | ||
| if isinstance(x, int): | ||
| s = "{x:<{s}}".format( | ||
| x=x, | ||
| s=self._default_cell_size, | ||
| ) | ||
| s = f"{x:<{self._default_cell_size}}" | ||
| else: | ||
| s = "{x:<{s}.{p}}".format( | ||
| x=x, | ||
| s=self._default_cell_size, | ||
| p=self._default_precision, | ||
| ) | ||
| s = f"{x:<{self._default_cell_size}.{self._default_precision}}" | ||
|
|
||
| if len(s) > self._default_cell_size: | ||
| if "." in s: | ||
| return s[:self._default_cell_size] | ||
| else: | ||
| return s[:self._default_cell_size - 3] + "..." | ||
| return s[:self._default_cell_size - 3] + "..." | ||
| return s | ||
|
|
||
| def _format_bool(self, x): | ||
| """Format a boolean. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| x : boolean | ||
|
|
||
|
|
||
| Returns | ||
| ------- | ||
| A stringified, formatted version of `x`. | ||
| """ | ||
| if 5 > self._default_cell_size: | ||
| if x == True: | ||
| if x: | ||
| x_ = 'T' | ||
| elif x == False: | ||
| else: | ||
| x_ = 'F' | ||
| else: | ||
| x_ = str(x) | ||
| s = "{x:<{s}}".format( | ||
| x=x_, | ||
| s=self._default_cell_size, | ||
| ) | ||
| s = f"{x_:<{self._default_cell_size}}" | ||
| return s | ||
|
|
||
| def _format_key(self, key): | ||
| s = "{key:^{s}}".format( | ||
| key=key, | ||
| s=self._default_cell_size | ||
| ) | ||
| """Format a key. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| key : string | ||
|
|
||
|
|
||
| Returns | ||
| ------- | ||
| A stringified, formatted version of `x`. | ||
| """ | ||
| s = f"{key:^{self._default_cell_size}}" | ||
| if len(s) > self._default_cell_size: | ||
| return s[:self._default_cell_size - 3] + "..." | ||
| return s | ||
|
|
||
| def _step(self, instance, colour=Colours.black): | ||
| def _step(self, instance, colour=Fore.BLACK): | ||
| """Log a step. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| instance : bayesian_optimization.BayesianOptimization | ||
| The instance associated with the event. | ||
|
|
||
| colour : | ||
| (Default value = Fore.BLACK) | ||
|
|
||
| Returns | ||
| ------- | ||
| A stringified, formatted version of the most recent optimization step. | ||
| """ | ||
| res = instance.res[-1] | ||
| cells = [] | ||
|
|
||
|
|
@@ -89,9 +162,20 @@ def _step(self, instance, colour=Colours.black): | |
| for key in instance.space.keys: | ||
| cells.append(self._format_number(res["params"][key])) | ||
|
|
||
| return "| " + " | ".join(map(colour, cells)) + " |" | ||
| return "| " + " | ".join([colour + cells[i] for i in range(len(cells))]) + " |" | ||
|
|
||
| def _header(self, instance): | ||
| """Print the header of the log. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| instance : bayesian_optimization.BayesianOptimization | ||
| The instance associated with the header. | ||
|
|
||
| Returns | ||
| ------- | ||
| A stringified, formatted version of the most header. | ||
| """ | ||
| cells = [] | ||
| cells.append(self._format_key("iter")) | ||
| cells.append(self._format_key("target")) | ||
|
|
@@ -107,6 +191,17 @@ def _header(self, instance): | |
| return line + "\n" + ("-" * self._header_length) | ||
|
|
||
| def _is_new_max(self, instance): | ||
| """Check if the step to log produced a new maximum. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| instance : bayesian_optimization.BayesianOptimization | ||
| The instance associated with the step. | ||
|
|
||
| Returns | ||
| ------- | ||
| boolean | ||
| """ | ||
| if instance.max is None: | ||
| # During constrained optimization, there might not be a maximum | ||
| # value since the optimizer might've not encountered any points | ||
|
|
@@ -117,14 +212,25 @@ def _is_new_max(self, instance): | |
| return instance.max["target"] > self._previous_max | ||
|
|
||
| def update(self, event, instance): | ||
| """Handle incoming events. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| event : str | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this a string or an
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These |
||
| One of the values associated with `Events.OPTIMIZATION_START`, | ||
| `Events.OPTIMIZATION_STEP` or `Events.OPTIMIZATION_END`. | ||
|
|
||
| instance : bayesian_optimization.BayesianOptimization | ||
| The instance associated with the step. | ||
| """ | ||
| if event == Events.OPTIMIZATION_START: | ||
| line = self._header(instance) + "\n" | ||
| elif event == Events.OPTIMIZATION_STEP: | ||
| is_new_max = self._is_new_max(instance) | ||
| if self._verbose == 1 and not is_new_max: | ||
| line = "" | ||
| else: | ||
| colour = Colours.purple if is_new_max else Colours.black | ||
| colour = Fore.MAGENTA if is_new_max else Fore.BLACK | ||
| line = self._step(instance, colour=colour) + "\n" | ||
| elif event == Events.OPTIMIZATION_END: | ||
| line = "=" * self._header_length + "\n" | ||
|
|
@@ -135,18 +241,43 @@ def update(self, event, instance): | |
|
|
||
|
|
||
| class JSONLogger(_Tracker): | ||
| def __init__(self, path, reset=True): | ||
| """ | ||
| Logger that outputs steps in JSON format. | ||
|
|
||
| The resulting file can be used to restart the optimization from an earlier state. | ||
| """ | ||
|
|
||
| def __init__(self, path, reset=True): | ||
| """ | ||
| Initialize the logger. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| path : str or bytes or os.PathLike | ||
|
|
||
| """ | ||
| self._path = path | ||
| if reset: | ||
| try: | ||
| os.remove(self._path) | ||
| except OSError: | ||
| pass | ||
| super(JSONLogger, self).__init__() | ||
| super().__init__() | ||
|
|
||
| def update(self, event, instance): | ||
| """ | ||
| Handle incoming events. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| event : str | ||
| One of the values associated with `Events.OPTIMIZATION_START`, | ||
| `Events.OPTIMIZATION_STEP` or `Events.OPTIMIZATION_END`. | ||
|
|
||
| instance : bayesian_optimization.BayesianOptimization | ||
| The instance associated with the step. | ||
|
|
||
| """ | ||
| if event == Events.OPTIMIZATION_STEP: | ||
|
Comment on lines
+271
to
281
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same thing here, it seems that we expect |
||
| data = dict(instance.res[-1]) | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These two codes have different behavior, it seems that the old one was intently done with if / elif.
But it can be as surprising as this:
Or even
In the previous code it would ignore anything that's not a boolean
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you're giving me too much credit here 🙃
I do see how this could potentially print something wrong if called with the wrong argument type. What do you think would be the best way to handle this case?