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 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/bayesian_optimization.py b/bayes_opt/bayesian_optimization.py index 97a7b9de1..da0702a8d 100644 --- a/bayes_opt/bayesian_optimization.py +++ b/bayes_opt/bayesian_optimization.py @@ -1,3 +1,8 @@ +"""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 +17,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 +48,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 +56,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. @@ -150,7 +164,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 @@ -167,30 +182,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 at the given points. + + Useful to guide the optimizer. Parameters ---------- @@ -201,7 +239,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: @@ -209,7 +246,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()) @@ -233,7 +277,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) @@ -257,10 +307,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 ---------- @@ -318,8 +366,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 ---------- @@ -329,5 +376,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/event.py b/bayes_opt/event.py index d5dfdd10e..374534343 100644 --- a/bayes_opt/event.py +++ b/bayes_opt/event.py @@ -1,4 +1,11 @@ +"""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' 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