From 11a0c6aba1fcc6b5d2716052da5222a84259c5b9 Mon Sep 17 00:00:00 2001 From: YoungJae Bae <57710489+YoungJaeBae@users.noreply.github.com> Date: Fri, 14 Jul 2023 15:46:40 +0900 Subject: [PATCH 1/7] Fixes issue-436: Constrained optimization does not allow duplicate points (#437) --- bayes_opt/bayesian_optimization.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index 97a7b9de1..364e1c822 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -150,7 +150,8 @@ def __init__(self, f, pbounds, constraint=constraint_, - random_state=random_state + random_state=random_state, + allow_duplicate_points=self._allow_duplicate_points ) self.is_constrained = True From 4445c030b012f4d3d0dc2ddb9ffc07987d25a2b9 Mon Sep 17 00:00:00 2001 From: till-m Date: Tue, 10 Oct 2023 16:13:15 +0200 Subject: [PATCH 2/7] Update docs of `bayesian_optimization.py` and `observer.py`. --- bayes_opt/bayesian_optimization.py | 81 +++++++++++++++++++++++------- bayes_opt/observer.py | 23 ++++++--- 2 files changed, 78 insertions(+), 26 deletions(-) diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index 364e1c822..7a45edad6 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -1,3 +1,7 @@ +"""Main module. + +Holds the `BayesianOptimization` class, which handles the maximization of a +function over a specific target space.""" import warnings from bayes_opt.constraint import ConstraintModel @@ -12,17 +16,25 @@ class Queue: + """Queue datastructure. + + Append items in the end, remove items from the front. + """ + def __init__(self): self._queue = [] @property def empty(self): + """Check whether the queue holds any items.""" return len(self) == 0 def __len__(self): + """Return number of items in the Queue.""" return len(self._queue) def __next__(self): + """Remove and return first item in the Queue.""" if self.empty: raise StopIteration("Queue is empty, no more objects to retrieve.") obj = self._queue[0] @@ -35,11 +47,7 @@ def add(self, obj): class Observable(object): - """ - - Inspired/Taken from - https://www.protechtraining.com/blog/post/879#simple-observer - """ + """Inspired by https://www.protechtraining.com/blog/post/879#simple-observer.""" def __init__(self, events): # maps event names to subscribers @@ -47,23 +55,28 @@ def __init__(self, events): self._events = {event: dict() for event in events} def get_subscribers(self, event): + """Return the subscribers of an event.""" return self._events[event] def subscribe(self, event, subscriber, callback=None): + """Add subscriber to an event.""" if callback is None: callback = getattr(subscriber, 'update') self.get_subscribers(event)[subscriber] = callback def unsubscribe(self, event, subscriber): + """Remove a subscriber for a particular event.""" del self.get_subscribers(event)[subscriber] def dispatch(self, event): + """Trigger callbacks for subscribers of an event.""" for _, callback in self.get_subscribers(event).items(): callback(event, self) class BayesianOptimization(Observable): - """ + """Handle optimization of a target function over a specific target space. + This class takes the function to optimize as well as the parameters bounds in order to find which values for the parameters yield the maximum value using bayesian optimization. @@ -168,30 +181,53 @@ def __init__(self, @property def space(self): + """Return the target space associated with the optimizer.""" return self._space @property def constraint(self): + """Return the constraint associated with the optimizer, if any.""" if self.is_constrained: return self._space.constraint return None @property def max(self): + """Get maximum target value found and corresponding parameters. + + See `TargetSpace.max` for more information. + """ return self._space.max() @property def res(self): + """Get all target values and constraint fulfillment for all parameters. + + See `TargetSpace.res` for more information. + """ return self._space.res() def register(self, params, target, constraint_value=None): - """Expect observation with known target""" + """Register an observation with known target. + + Parameters + ---------- + params: dict or list + The parameters associated with the observation. + + target: float + Value of the target function at the observation. + + constraint_value: float or None + Value of the constraint function at the observation, if any. + """ self._space.register(params, target, constraint_value) self.dispatch(Events.OPTIMIZATION_STEP) def probe(self, params, lazy=True): - """ - Evaluates the function on the given points. Useful to guide the optimizer. + """Evaluate the function on the given points. + + Useful to guide the optimizer. Parameters ---------- @@ -202,7 +238,6 @@ def probe(self, params, lazy=True): If True, the optimizer will evaluate the points when calling maximize(). Otherwise it will evaluate it at the moment. """ - if lazy: self._queue.add(params) else: @@ -210,7 +245,14 @@ def probe(self, params, lazy=True): self.dispatch(Events.OPTIMIZATION_STEP) def suggest(self, utility_function): - """Most promising point to probe next""" + """Suggest a promising point to probe next. + + Parameters + ---------- + utility_function: + Surrogate function which suggests parameters to probe the target + function at. + """ if len(self._space) == 0: return self._space.array_to_params(self._space.random_sample()) @@ -234,7 +276,13 @@ def suggest(self, utility_function): return self._space.array_to_params(suggestion) def _prime_queue(self, init_points): - """Make sure there's something in the queue at the very beginning.""" + """Ensure the queue is not empty. + + Parameters + ---------- + init_points: int + Number of parameters to prime the queue with. + """ if self._queue.empty and self._space.empty: init_points = max(init_points, 1) @@ -258,10 +306,8 @@ def maximize(self, kappa_decay_delay=None, xi=None, **gp_params): - """ - Probes the target space to find the parameters that yield the maximum - value for the given function. + Maximize the given function over the target space. Parameters ---------- @@ -319,8 +365,7 @@ def maximize(self, self.dispatch(Events.OPTIMIZATION_END) def set_bounds(self, new_bounds): - """ - A method that allows changing the lower and upper searching bounds + """Modify the bounds of the search space. Parameters ---------- @@ -330,5 +375,5 @@ def set_bounds(self, new_bounds): self._space.set_bounds(new_bounds) def set_gp_params(self, **params): - """Set parameters to the internal Gaussian Process Regressor""" + """Set parameters of the internal Gaussian Process Regressor.""" self._gp.set_params(**params) diff --git a/bayes_opt/observer.py b/bayes_opt/observer.py index 5a6ac16b2..910b8c370 100644 --- a/bayes_opt/observer.py +++ b/bayes_opt/observer.py @@ -1,16 +1,11 @@ -""" -observers... -""" +"""Holds the parent class for loggers.""" from datetime import datetime from .event import Events -class Observer: - def update(self, event, instance): - raise NotImplementedError - - class _Tracker(object): + """Parent class for ScreenLogger and JSONLogger.""" + def __init__(self): self._iterations = 0 @@ -21,6 +16,17 @@ def __init__(self): self._previous_time = None def _update_tracker(self, event, instance): + """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 @@ -35,6 +41,7 @@ def _update_tracker(self, event, instance): self._previous_max_params = current_max["params"] def _time_metrics(self): + """Return time passed since last call.""" now = datetime.now() if self._start_time is None: self._start_time = now From e5ba44a1962eb8abbfd550c9d2da6cc4f0a2582b Mon Sep 17 00:00:00 2001 From: till-m Date: Tue, 10 Oct 2023 16:21:20 +0200 Subject: [PATCH 3/7] Fix minor style issue in module docstring --- bayes_opt/bayesian_optimization.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index 7a45edad6..de2a12d96 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -1,7 +1,8 @@ """Main module. Holds the `BayesianOptimization` class, which handles the maximization of a -function over a specific target space.""" +function over a specific target space. +""" import warnings from bayes_opt.constraint import ConstraintModel From bbdd6aaa4de103f7d28d9345c6b7002dca61883d Mon Sep 17 00:00:00 2001 From: till-m Date: Tue, 10 Oct 2023 16:49:58 +0200 Subject: [PATCH 4/7] Update docs of `__init__.py` and `events.py`. --- bayes_opt/__init__.py | 1 + bayes_opt/event.py | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/bayes_opt/__init__.py b/bayes_opt/__init__.py index 3c9d4791c..50cd81bcb 100644 --- a/bayes_opt/__init__.py +++ b/bayes_opt/__init__.py @@ -1,3 +1,4 @@ +"""Pure Python implementation of bayesian global optimization with gaussian processes.""" from .bayesian_optimization import BayesianOptimization, Events from .domain_reduction import SequentialDomainReductionTransformer from .util import UtilityFunction diff --git a/bayes_opt/event.py b/bayes_opt/event.py index d5dfdd10e..d8fcf752e 100644 --- a/bayes_opt/event.py +++ b/bayes_opt/event.py @@ -1,4 +1,10 @@ +"""Register optimization events variables.""" + class Events: + """Define optimization events. + + Behaves similar to enums.""" + OPTIMIZATION_START = 'optimization:start' OPTIMIZATION_STEP = 'optimization:step' OPTIMIZATION_END = 'optimization:end' From c1368ddf33fc352c0f1f1d01fef2f29e93afd182 Mon Sep 17 00:00:00 2001 From: till-m Date: Tue, 10 Oct 2023 16:52:32 +0200 Subject: [PATCH 5/7] Fix minor style issue in class docstring --- bayes_opt/event.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bayes_opt/event.py b/bayes_opt/event.py index d8fcf752e..374534343 100644 --- a/bayes_opt/event.py +++ b/bayes_opt/event.py @@ -3,7 +3,8 @@ class Events: """Define optimization events. - Behaves similar to enums.""" + Behaves similar to enums. + """ OPTIMIZATION_START = 'optimization:start' OPTIMIZATION_STEP = 'optimization:step' From c5906f4a3647b66b2a53ee1b64dfd22ebb0f851c Mon Sep 17 00:00:00 2001 From: till-m Date: Tue, 10 Oct 2023 16:53:56 +0200 Subject: [PATCH 6/7] Add workflow to check docstrings --- .github/workflows/check_docstrings.yml | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/workflows/check_docstrings.yml diff --git a/.github/workflows/check_docstrings.yml b/.github/workflows/check_docstrings.yml new file mode 100644 index 000000000..4f6e8ce94 --- /dev/null +++ b/.github/workflows/check_docstrings.yml @@ -0,0 +1,30 @@ +# This workflow will install Python dependencies and check docstrings with a single version of Python +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: Check docstrings + +on: + push: + branches: [ "master" ] + pull_request: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python 3.10 + uses: actions/setup-python@v3 + with: + python-version: "3.10" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pydocstyle + - name: Check docstyle + run : pydocstyle --convention=numpy bayes_opt/* + #- name: Run linting + # run : pylint bayes_opt/* --disable=C0103 # ignore no snake_case conformity of arguments From 6aca15dd4bcd76a66942266444e242ea3e544cc7 Mon Sep 17 00:00:00 2001 From: till-m <36440677+till-m@users.noreply.github.com> Date: Wed, 11 Oct 2023 09:07:57 +0200 Subject: [PATCH 7/7] Update bayes_opt/bayesian_optimization.py Co-authored-by: Leandro Braga <18340809+leandrobbraga@users.noreply.github.com> --- bayes_opt/bayesian_optimization.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bayes_opt/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index de2a12d96..da0702a8d 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -226,7 +226,7 @@ def register(self, params, target, constraint_value=None): self.dispatch(Events.OPTIMIZATION_STEP) def probe(self, params, lazy=True): - """Evaluate the function on the given points. + """Evaluate the function at the given points. Useful to guide the optimizer.