Skip to content

Commit

Permalink
Switch code formatter to ruff (#2582)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: #2582

Use the ruff code formatter. This diff

- Changes the Meta-internal config to use ruff.
- Updates `pyproject.toml` to use ruff as the code formatter.
- Applies the new formatting across the codebase.

This does NOT change the code sorting engine (that is still usort). We can update that in a next step.

Reviewed By: saitcakmak

Differential Revision: D64517061

fbshipit-source-id: bf9a4ed258b9489fc757c810fe8bbff0a5d018c4
  • Loading branch information
Balandat authored and facebook-github-bot committed Oct 17, 2024
1 parent b672626 commit d2c6f5e
Show file tree
Hide file tree
Showing 67 changed files with 40 additions and 119 deletions.
1 change: 1 addition & 0 deletions botorch/acquisition/cached_cholesky.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Abstract class for acquisition functions leveraging a cached Cholesky
decomposition of the posterior covariance over f(X_baseline).
"""

from __future__ import annotations

import warnings
Expand Down
1 change: 0 additions & 1 deletion botorch/acquisition/fixed_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ def __init__(
if isinstance(values, Tensor):
new_values = values.detach().clone()
else:

dtype = get_dtype_of_sequence(values)
device = get_device_of_sequence(values)

Expand Down
2 changes: 0 additions & 2 deletions botorch/acquisition/input_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1258,7 +1258,6 @@ def construct_inputs_qKG(
}

if with_current_value:

X = _get_dataset_field(training_data, "X", first_only=True)
_bounds = torch.as_tensor(bounds, dtype=X.dtype, device=X.device)

Expand Down Expand Up @@ -1868,7 +1867,6 @@ def _get_ref_point(
objective_thresholds: Tensor,
objective: MCMultiOutputObjective | None = None,
) -> Tensor:

if objective is None:
ref_point = objective_thresholds
elif isinstance(objective, RiskMeasureMCObjective):
Expand Down
1 change: 0 additions & 1 deletion botorch/acquisition/multi_objective/analytic.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
"""


from __future__ import annotations

from itertools import product
Expand Down
1 change: 0 additions & 1 deletion botorch/acquisition/multi_objective/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
Base classes for multi-objective acquisition functions.
"""


from __future__ import annotations

from abc import ABC, abstractmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
2022.
"""

from __future__ import annotations

from abc import abstractmethod
Expand Down
2 changes: 0 additions & 2 deletions botorch/acquisition/multi_objective/logei.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
class qLogExpectedHypervolumeImprovement(
MultiObjectiveMCAcquisitionFunction, SubsetIndexCachingMixin
):

_log: bool = True

def __init__(
Expand Down Expand Up @@ -321,7 +320,6 @@ class qLogNoisyExpectedHypervolumeImprovement(
NoisyExpectedHypervolumeMixin,
qLogExpectedHypervolumeImprovement,
):

_log: bool = True

def __init__(
Expand Down
1 change: 1 addition & 0 deletions botorch/acquisition/prior_guided.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Augmenting Acquisition Functions with User Beliefs for Bayesian Optimization.
ICLR 2022.
"""

from __future__ import annotations

from botorch.acquisition.acquisition import AcquisitionFunction
Expand Down
1 change: 1 addition & 0 deletions botorch/exceptions/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
r"""
Botorch Warnings.
"""

import warnings


Expand Down
2 changes: 1 addition & 1 deletion botorch/generation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


def _convert_nonlinear_inequality_constraints(
nonlinear_inequality_constraints: list[Callable | tuple[Callable, bool]]
nonlinear_inequality_constraints: list[Callable | tuple[Callable, bool]],
) -> list[tuple[Callable, bool]]:
"""Convert legacy defintions of nonlinear inequality constraints into the new
format. Assumes intra-point constraints.
Expand Down
1 change: 0 additions & 1 deletion botorch/models/fully_bayesian.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
Seventh Conference on Uncertainty in Artificial Intelligence, 2021.
"""


import math
from abc import abstractmethod
from collections.abc import Mapping
Expand Down
4 changes: 1 addition & 3 deletions botorch/models/fully_bayesian_multitask.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
# LICENSE file in the root directory of this source tree.


r"""Multi-task Gaussian Process Regression models with fully Bayesian inference.
"""

r"""Multi-task Gaussian Process Regression models with fully Bayesian inference."""

from collections.abc import Mapping
from typing import Any, NoReturn
Expand Down
5 changes: 2 additions & 3 deletions botorch/models/gp_regression_mixed.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,8 @@ def __init__(
train_Y: Tensor,
cat_dims: list[int],
train_Yvar: Tensor | None = None,
cont_kernel_factory: None | (
Callable[[torch.Size, int, list[int]], Kernel]
) = None,
cont_kernel_factory: None
| (Callable[[torch.Size, int, list[int]], Kernel]) = None,
likelihood: Likelihood | None = None,
outcome_transform: OutcomeTransform | _DefaultType | None = DEFAULT,
input_transform: InputTransform | None = None, # TODO
Expand Down
3 changes: 2 additions & 1 deletion botorch/models/kernels/contextual_lcea.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,8 @@ def _eval_context_covar(self) -> Tensor:
else:
context_outputscales = self.outputscale_list * self.context_weight
context_covar = (
(context_outputscales.unsqueeze(-2)) # (ns) x 1 x num_contexts
(context_outputscales.unsqueeze(-2))
# (ns) x 1 x num_contexts
.mul(context_covar)
.mul(context_outputscales.unsqueeze(-1)) # (ns) x num_contexts x 1
)
Expand Down
1 change: 1 addition & 0 deletions botorch/models/transforms/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
is typically part of a Model and applied within the model.forward()
method.
"""

from __future__ import annotations

from abc import ABC, abstractmethod
Expand Down
1 change: 1 addition & 0 deletions botorch/optim/initializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
surrogates and dynamic coordinate search in high-dimensional
expensive black-box optimization, Engineering Optimization, 2013.
"""

from __future__ import annotations

import warnings
Expand Down
2 changes: 1 addition & 1 deletion botorch/optim/parameter_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ def _generate_unfixed_nonlin_constraints(
values = torch.tensor(list(fixed_features.values()), dtype=torch.double)

def _wrap_nonlin_constraint(
constraint: Callable[[Tensor], Tensor]
constraint: Callable[[Tensor], Tensor],
) -> Callable[[Tensor], Tensor]:
def new_nonlin_constraint(X: Tensor) -> Tensor:
ivalues = values.to(X).expand(*X.shape[:-1], len(fixed_features))
Expand Down
1 change: 0 additions & 1 deletion botorch/optim/utils/timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ def minimize_with_timeout(
track of the runtime and the optimization variables at the current iteration.
"""
if timeout_sec is not None:

start_time = time.monotonic()
callback_data = {"num_iterations": 0} # update from withing callback below

Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/ensemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def variance(self) -> Tensor:
return self.values.var(dim=-3)

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the posterior with
the given `sample_shape`.
Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/gpytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ def batch_range(self) -> tuple[int, int]:
return (0, -1)

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the posterior with
the given `sample_shape`.
Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/higher_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ def batch_range(self) -> tuple[int, int]:
return (0, -1)

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the posterior with
the given `sample_shape`.
Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/posterior.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def density(self, value: Tensor) -> Tensor:
) # pragma: no cover

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the posterior with
the given `sample_shape`.
Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/posterior_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def dtype(self) -> torch.dtype:
return next(iter(dtypes))

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the posterior with
the given `sample_shape`.
Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ def density(self, value: Tensor) -> Tensor:
return self.log_prob(value).exp()

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the distribution with
the given `sample_shape`.
Expand Down
3 changes: 2 additions & 1 deletion botorch/posteriors/transformed.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ def dtype(self) -> torch.dtype:
return self._posterior.dtype

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
r"""Returns the shape of the samples produced by the posterior with
the given `sample_shape`.
Expand Down
1 change: 0 additions & 1 deletion botorch/sampling/pathwise/prior_samplers.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ def _draw_kernel_feature_paths_fallback(
output_transform: TOutputTransform | None = None,
weight_generator: Callable[[Size], Tensor] | None = None,
) -> GeneralizedLinearPath:

# Generate a kernel feature map
feature_map = map_generator(
kernel=covar_module,
Expand Down
1 change: 0 additions & 1 deletion botorch/test_functions/multi_objective.py
Original file line number Diff line number Diff line change
Expand Up @@ -1267,7 +1267,6 @@ def evaluate_slack_true(self, X: Tensor) -> Tensor:


class C2DTLZ2(DTLZ2, ConstrainedBaseTestProblem):

num_constraints = 1
_r = 0.2
# approximate from nsga-ii, TODO: replace with analytic
Expand Down
7 changes: 0 additions & 7 deletions botorch/test_functions/synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class Beale(SyntheticTestFunction):

dim = 2
_optimal_value = 0.0
_bounds = [(-4.5, 4.5), (-4.5, 4.5)]
Expand Down Expand Up @@ -207,7 +206,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class Bukin(SyntheticTestFunction):

dim = 2
_bounds = [(-15.0, -5.0), (-3.0, 3.0)]
_optimal_value = 0.0
Expand Down Expand Up @@ -241,7 +239,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class DropWave(SyntheticTestFunction):

dim = 2
_bounds = [(-5.12, 5.12), (-5.12, 5.12)]
_optimal_value = -1.0
Expand All @@ -256,7 +253,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class DixonPrice(SyntheticTestFunction):

_optimal_value = 0.0

def __init__(
Expand Down Expand Up @@ -639,7 +635,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class Rastrigin(SyntheticTestFunction):

_optimal_value = 0.0

def __init__(
Expand Down Expand Up @@ -764,7 +759,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class SixHumpCamel(SyntheticTestFunction):

dim = 2
_bounds = [(-3.0, 3.0), (-2.0, 2.0)]
_optimal_value = -1.0316
Expand Down Expand Up @@ -815,7 +809,6 @@ def evaluate_true(self, X: Tensor) -> Tensor:


class ThreeHumpCamel(SyntheticTestFunction):

dim = 2
_bounds = [(-5.0, 5.0), (-5.0, 5.0)]
_optimal_value = 0.0
Expand Down
1 change: 1 addition & 0 deletions botorch/test_utils/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Utilities for speeding up optimization in tests.
"""

from __future__ import annotations

from collections.abc import Generator
Expand Down
2 changes: 1 addition & 1 deletion botorch/utils/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@


def get_outcome_constraint_transforms(
outcome_constraints: tuple[Tensor, Tensor] | None
outcome_constraints: tuple[Tensor, Tensor] | None,
) -> list[Callable[[Tensor], Tensor]] | None:
r"""Create outcome constraint callables from outcome constraint tensors.
Expand Down
1 change: 0 additions & 1 deletion botorch/utils/multi_objective/box_decompositions/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

r"""Utilities for box decomposition algorithms."""


import torch
from botorch.exceptions.errors import BotorchTensorDimensionError, UnsupportedError
from botorch.utils.multi_objective.pareto import is_non_dominated
Expand Down
1 change: 1 addition & 0 deletions botorch/utils/multi_objective/scalarization.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
for expensive multiobjective optimization problems," in IEEE Transactions
on Evolutionary Computation, vol. 10, no. 1, pp. 50-66, Feb. 2006.
"""

from __future__ import annotations

from collections.abc import Callable
Expand Down
1 change: 0 additions & 1 deletion botorch/utils/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@


def _get_mcmc_samples(num_samples: int, dim: int, infer_noise: bool, **tkwargs):

mcmc_samples = {
"lengthscale": 1 + torch.rand(num_samples, 1, dim, **tkwargs),
"outputscale": 1 + torch.rand(num_samples, **tkwargs),
Expand Down
3 changes: 2 additions & 1 deletion botorch/utils/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,8 @@ def batch_shape(self) -> torch.Size:
raise NotImplementedError # pragma: no cover

def _extended_shape(
self, sample_shape: torch.Size = torch.Size() # noqa: B008
self,
sample_shape: torch.Size = torch.Size(), # noqa: B008
) -> torch.Size:
return sample_shape + self.base_sample_shape

Expand Down
3 changes: 1 addition & 2 deletions botorch/utils/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ def decorator(
def decorated(
acqf: AcquisitionFunction, X: Any, *args: Any, **kwargs: Any
) -> Any:

# Allow using acquisition functions for other inputs (e.g. lists of strings)
if not isinstance(X, Tensor):
return method(acqf, X, *args, **kwargs)
Expand Down Expand Up @@ -311,7 +310,7 @@ def decorated(


def concatenate_pending_points(
method: Callable[[Any, Tensor], Any]
method: Callable[[Any, Tensor], Any],
) -> Callable[[Any, Tensor], Any]:
r"""Decorator concatenating X_pending into an acquisition function's argument.
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ write_to = "./botorch/version.py"

[tool.usort]
first_party_detection = false

[tool.ufmt]
formatter = "ruff-api"
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,7 @@ def test_evaluate_q_hvkg(self):
ModelListGP, "fantasize", return_value=mfm
) as patch_f, mock.patch(
NO, new_callable=mock.PropertyMock
) as mock_num_outputs, warnings.catch_warnings(
record=True
) as ws:
) as mock_num_outputs, warnings.catch_warnings(record=True) as ws:
mock_num_outputs.return_value = 3
qHVKG = acqf_class(
model=model,
Expand Down
Loading

0 comments on commit d2c6f5e

Please sign in to comment.