Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 161 additions & 30 deletions bayes_opt/logger.py
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:
Comment on lines +112 to +114

@leandrobbraga leandrobbraga Jul 20, 2023 •

Copy link
Copy Markdown
Contributor

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.

>>> x = "false"
>>> if x:
...    print("got 'true'!")
... else:
...    print("got 'false'!)
...
got 'true'!

But it can be as surprising as this:

>>> x = 0
>>> if x:
...    print("got 'true'!")
... else:
...    print("got 'false'!)
...
got 'false'!

Or even

>>> x = []
>>> if x:
...    print("got 'true'!")
... else:
...    print("got 'false'!)
...
got 'false'!

In the previous code it would ignore anything that's not a boolean

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it seems that the old one was intently done with if / elif

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?

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 = []

Expand All @@ -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"))
Expand All @@ -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
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a string or an Events object? By looking at the code it is comparing event == Events.OPTIMIZATION_START, which implies that it is an Events object.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These Events.OPTIMIZATION_START etc. are properties of the events classed with assigned string values optimization:start etc. I thought about going for Event as type, but that is technically not correct. Maybe it would be good to define Events as a proper Enum but I wouldn't do that in this PR.

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"
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing here, it seems that we expect event to be of Events type

data = dict(instance.res[-1])

Expand Down
6 changes: 3 additions & 3 deletions bayes_opt/target_space.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy as np
from .util import ensure_rng, NotUniqueError
from .util import Colours
from colorama import Fore


def _hashable(x):
Expand Down Expand Up @@ -188,8 +188,8 @@ def register(self, params, target, constraint_value=None):
if x in self:
if self._allow_duplicate_points:
self.n_duplicate_points = self.n_duplicate_points + 1
print(f'{Colours.RED}Data point {x} is not unique. {self.n_duplicate_points} duplicates registered.'
f' Continuing ...{Colours.END}')
print(Fore.RED + f'Data point {x} is not unique. {self.n_duplicate_points} duplicates registered.'
f' Continuing ...')
else:
raise NotUniqueError(f'Data point {x} is not unique. You can set "allow_duplicate_points=True" to '
f'avoid this error')
Expand Down
Loading