File: observer.py

package info (click to toggle)
python-bayesian-optimization 2.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 19,816 kB
  • sloc: python: 2,820; makefile: 26; sh: 9
file content (62 lines) | stat: -rw-r--r-- 1,927 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""Holds the parent class for loggers."""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING

from bayes_opt.event import Events

if TYPE_CHECKING:
    from bayes_opt.bayesian_optimization import BayesianOptimization


class _Tracker:
    """Parent class for ScreenLogger and JSONLogger."""

    def __init__(self) -> None:
        self._iterations = 0

        self._previous_max = None
        self._previous_max_params = None

        self._start_time = None
        self._previous_time = None

    def _update_tracker(self, event: str, instance: BayesianOptimization) -> None:
        """Update the tracker.

        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:
            self._iterations += 1

            if instance.max is None:
                return

            current_max = instance.max

            if self._previous_max is None or current_max["target"] > self._previous_max:
                self._previous_max = current_max["target"]
                self._previous_max_params = current_max["params"]

    def _time_metrics(self) -> tuple[str, float, float]:
        """Return time passed since last call."""
        now = datetime.now()  # noqa: DTZ005
        if self._start_time is None:
            self._start_time = now
        if self._previous_time is None:
            self._previous_time = now

        time_elapsed = now - self._start_time
        time_delta = now - self._previous_time

        self._previous_time = now
        return (now.strftime("%Y-%m-%d %H:%M:%S"), time_elapsed.total_seconds(), time_delta.total_seconds())