From b3a6bf90c361e89d1a0d2f7a21642a5ec875de2e Mon Sep 17 00:00:00 2001 From: Behrang Shafei <50267830+bertiqwerty@users.noreply.github.com> Date: Wed, 10 May 2023 22:42:14 +0200 Subject: [PATCH] replaced flake8 and isort with ruff (#197) * replaced flake8 and isort with ruff * added isort checks to ruff * Enforce B008 * Enforce E731 * Enforce C413 * Enforce C414 * Enforce C416 * Enforce C419 * Enforce B006 * Enforce B007 --------- Co-authored-by: WalzDS --- .github/workflows/lint.yaml | 7 ++-- .pre-commit-config.yaml | 22 ++++--------- bofire/benchmarks/aspen_benchmark.py | 4 +-- bofire/benchmarks/multi.py | 15 +++++---- bofire/benchmarks/single.py | 4 ++- bofire/data_models/domain/domain.py | 2 +- bofire/data_models/domain/features.py | 8 ++--- bofire/data_models/features/categorical.py | 10 +++--- bofire/data_models/features/descriptor.py | 10 +++--- bofire/plot/objective.py | 4 +-- bofire/plot/prior.py | 6 ++-- bofire/strategies/doe/design.py | 14 ++++---- bofire/strategies/doe/utils.py | 2 +- bofire/surrogates/cloudpickle_module.py | 2 +- bofire/surrogates/diagnostics.py | 4 +-- bofire/surrogates/mlp.py | 4 +-- bofire/surrogates/surrogate.py | 2 +- bofire/surrogates/trainable.py | 32 +++++++++++-------- bofire/utils/doe.py | 20 ++++++++---- bofire/utils/reduce.py | 2 +- bofire/utils/torch_tools.py | 4 ++- pyproject.toml | 15 +++++++++ setup.cfg | 16 ---------- tests/bofire/data_models/specs/strategies.py | 2 -- .../test_constraint_fulfillment.py | 2 +- tests/bofire/data_models/test_features.py | 4 +-- tests/bofire/strategies/doe/test_design.py | 12 +++---- tests/bofire/strategies/test_base.py | 2 +- tests/bofire/strategies/test_doe.py | 4 +-- tests/bofire/strategies/test_qparego.py | 4 +-- tests/bofire/strategies/test_strategy.py | 2 +- .../surrogates/test_feature_importance.py | 2 +- 32 files changed, 122 insertions(+), 121 deletions(-) delete mode 100644 setup.cfg diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 5a5169ccd..1afda7ee7 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -9,7 +9,7 @@ on: jobs: style: - name: Check style with flake8, black, and isort + name: Check style with ruff and black runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -18,10 +18,9 @@ jobs: python-version: 3.9 - name: style run: | - pip3 install flake8==5.0.4 black==22.10.0 isort==5.12.0 - flake8 --verbose bofire tests + pip3 install ruff==0.0.265 black==22.10.0 black --check bofire tests - isort . --check-only --verbose + ruff check . pyright: name: Typechecking with pyright diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e69d81bbd..471744a09 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -7,21 +7,11 @@ repos: stages: [commit] entry: black types: [python] - - repo: https://github.com/pycqa/flake8 - rev: 5.0.4 + - repo: https://github.com/charliermarsh/ruff-pre-commit + # Ruff version. + rev: "v0.0.265" hooks: - - id: flake8 - name: flake8 - entry: flake8 - types: [python] - require_serial: true - - repo: https://github.com/pycqa/isort - rev: 5.12.0 - hooks: - - id: isort - name: isort - stages: [commit] - entry: isort - types: [python] - + - id: ruff + args: [--fix, --exit-non-zero-on-fix] + exclude: "README.md" diff --git a/bofire/benchmarks/aspen_benchmark.py b/bofire/benchmarks/aspen_benchmark.py index 83531a0bd..f9ecbb7d5 100644 --- a/bofire/benchmarks/aspen_benchmark.py +++ b/bofire/benchmarks/aspen_benchmark.py @@ -35,7 +35,7 @@ def __init__( filename: str, domain: Domain, paths: Dict[str, str], - additional_output_keys: List = [], + additional_output_keys: Optional[List] = None, translate_into_aspen_readable: Optional[ Callable[[Domain, pd.DataFrame], pd.DataFrame] ] = None, @@ -60,7 +60,7 @@ def __init__( self.translate_into_aspen_readable = translate_into_aspen_readable self._domain = domain - self.additional_output_keys = additional_output_keys + self.additional_output_keys = additional_output_keys or [] for key in self.domain.get_feature_keys(): # Check, if every input and output variable has a path to Aspen provided. diff --git a/bofire/benchmarks/multi.py b/bofire/benchmarks/multi.py index 187825b9e..080319948 100644 --- a/bofire/benchmarks/multi.py +++ b/bofire/benchmarks/multi.py @@ -174,12 +174,14 @@ class SnarBenchmark(Benchmark): Solving of a differential equation system with varying intitial values. """ - def __init__(self, C_i: Optional[np.ndarray] = np.ndarray((1, 1))): + def __init__(self, C_i: Optional[np.ndarray] = None): """Initializes multiobjective test function object of type SnarBenchmark. Args: C_i (Optional[np.ndarray]): Input concentrations. Defaults to [1, 1] """ + if C_i is None: + C_i = np.array([1, 1]) self.C_i = C_i # Decision variables @@ -224,7 +226,7 @@ def _f(self, candidates: pd.DataFrame) -> pd.DataFrame: """ stys = [] e_factors = [] - for i, candidate in candidates.iterrows(): + for _, candidate in candidates.iterrows(): tau = float(candidate["tau"]) equiv_pldn = float(candidate["equiv_pldn"]) conc_dfnb = float(candidate["conc_dfnb"]) @@ -297,11 +299,10 @@ def _integrand(self, t, C, T): T_ref = 90 + 273.71 # Convert to deg K T = T + 273.71 # Convert to deg K # Need to convert from 10^-2 M^-1s^-1 to M^-1min^-1 - k = ( - lambda k_ref, E_a, temp: 0.6 - * k_ref - * np.exp(-E_a / R * (1 / temp - 1 / T_ref)) - ) + + def k(k_ref, E_a, temp): + return 0.6 * k_ref * np.exp(-E_a / R * (1 / temp - 1 / T_ref)) + k_a = k(57.9, 33.3, T) k_b = k(2.70, 35.3, T) k_c = k(0.865, 38.9, T) diff --git a/bofire/benchmarks/single.py b/bofire/benchmarks/single.py index 40567164e..b47430837 100644 --- a/bofire/benchmarks/single.py +++ b/bofire/benchmarks/single.py @@ -52,7 +52,7 @@ def __init__( lower: float = -32.768, upper: float = 32.768, best_possible_f: float = 0.0, - evaluated_points=[], + evaluated_points: Optional[list] = None, ): """Initializes benchmark function of type Ackley. @@ -74,6 +74,8 @@ def __init__( self.lower = lower self.upper = upper self.best_possible_f = best_possible_f + if evaluated_points is None: + evaluated_points = [] self.evaluated_points = evaluated_points input_feature_list = [] diff --git a/bofire/data_models/domain/domain.py b/bofire/data_models/domain/domain.py index 62dc08753..4f1ddb63b 100644 --- a/bofire/data_models/domain/domain.py +++ b/bofire/data_models/domain/domain.py @@ -305,7 +305,7 @@ def get_nchoosek_combinations(self, exhaustive: bool = False): # noqa: C901 used_features_list.extend(itertools.combinations(con.features, n)) if con.none_also_valid: - used_features_list.append(tuple([])) + used_features_list.append(()) else: used_features_list.extend( itertools.combinations(con.features, con.max_count) diff --git a/bofire/data_models/domain/features.py b/bofire/data_models/domain/features.py index 51458c2bd..b26127418 100644 --- a/bofire/data_models/domain/features.py +++ b/bofire/data_models/domain/features.py @@ -433,7 +433,7 @@ def _validate_transform_specs(self, specs: TInputTransformSpecs): raise ValueError("Unknown features specified in transform specs.") # next check that all values are of type CategoricalEncodingEnum if not ( - all([isinstance(enc, CategoricalEncodingEnum) for enc in specs.values()]) + all(isinstance(enc, CategoricalEncodingEnum) for enc in specs.values()) ): raise ValueError("Unknown transform specified.") # next check that only Categoricalwithdescriptor have the value DESCRIPTOR @@ -477,12 +477,12 @@ def get_bounds( upper = [] for feat in self.get(): - l, u = feat.get_bounds( # type: ignore + lo, up = feat.get_bounds( # type: ignore transform_type=specs.get(feat.key), # type: ignore values=experiments[feat.key] if experiments is not None else None, ) - lower += l - upper += u + lower += lo + upper += up return lower, upper diff --git a/bofire/data_models/features/categorical.py b/bofire/data_models/features/categorical.py index 8eade29a3..ead548715 100644 --- a/bofire/data_models/features/categorical.py +++ b/bofire/data_models/features/categorical.py @@ -42,7 +42,7 @@ def validate_categories_unique(cls, categories): Returns: List[str]: List of the categories """ - categories = [name for name in categories] + categories = list(categories) if len(categories) != len(set(categories)): raise ValueError("categories must be unique") return categories @@ -180,9 +180,7 @@ def get_possible_categories(self, values: pd.Series) -> list: Returns: list: list of possible categories """ - return sorted( - list(set(list(set(values.tolist())) + self.get_allowed_categories())) - ) + return sorted(set(list(set(values.tolist())) + self.get_allowed_categories())) def to_onehot_encoding(self, values: pd.Series) -> pd.DataFrame: """Converts values to a one-hot encoding. @@ -368,7 +366,7 @@ def validate_categories_unique(cls, categories): Returns: List[str]: List of the categories """ - categories = [name for name in categories] + categories = list(categories) if len(categories) != len(set(categories)): raise ValueError("categories must be unique") return categories @@ -386,7 +384,7 @@ def validate_objective(cls, objective, values): def to_dict(self) -> Dict: """Returns the catergories and corresponding objective values as dictionary""" - return {cat: obj for cat, obj in zip(self.categories, self.objective)} + return dict(zip(self.categories, self.objective)) def __call__(self, values: pd.Series) -> pd.Series: return values.map(self.to_dict()).astype(float) diff --git a/bofire/data_models/features/descriptor.py b/bofire/data_models/features/descriptor.py index 2154bf64b..8bdd2fc3d 100644 --- a/bofire/data_models/features/descriptor.py +++ b/bofire/data_models/features/descriptor.py @@ -43,7 +43,7 @@ def descriptors_to_keys(cls, descriptors): Returns: List[str]: List of valid keys """ - return [name for name in descriptors] + return list(descriptors) @root_validator(pre=False, skip_on_failure=True) def validate_list_lengths(cls, values): @@ -104,7 +104,7 @@ def validate_descriptors(cls, descriptors): Returns: List[str]: List of the descriptors """ - descriptors = [name for name in descriptors] + descriptors = list(descriptors) if len(descriptors) != len(set(descriptors)): raise ValueError("descriptors must be unique") return descriptors @@ -133,7 +133,7 @@ def validate_values(cls, v, values): a = np.array(v) for i, d in enumerate(values["descriptors"]): if len(set(a[:, i])) == 1: - raise ValueError("No variation for descriptor {d}.") + raise ValueError(f"No variation for descriptor {d}.") return v def to_df(self): @@ -142,7 +142,7 @@ def to_df(self): Returns: pd.DataFrame: tabular overview of the feature as DataFrame """ - data = {cat: values for cat, values in zip(self.categories, self.values)} + data = dict(zip(self.categories, self.values)) return pd.DataFrame.from_dict(data, orient="index", columns=self.descriptors) def fixed_value( @@ -234,7 +234,7 @@ def to_descriptor_encoding(self, values: pd.Series) -> pd.DataFrame: """ return pd.DataFrame( data=values.map( - {cat: value for cat, value in zip(self.categories, self.values)} + dict(zip(self.categories, self.values)) ).values.tolist(), # type: ignore columns=[f"{self.key}{_CAT_SEP}{d}" for d in self.descriptors], index=values.index, diff --git a/bofire/plot/objective.py b/bofire/plot/objective.py index 9ee0837fc..fec5f690b 100644 --- a/bofire/plot/objective.py +++ b/bofire/plot/objective.py @@ -13,7 +13,7 @@ def plot_objective_plotly( lower: float, upper: float, values: Optional[pd.Series] = None, - layout_options: Dict = {}, + layout_options: Optional[Dict] = None, ): """Plot the assigned objective. @@ -43,7 +43,7 @@ def plot_objective_plotly( else: fig = fig1 - if len(layout_options) > 0: + if layout_options is not None: fig.update_layout(layout_options) return fig diff --git a/bofire/plot/prior.py b/bofire/plot/prior.py index e37d45826..3946ca7e8 100644 --- a/bofire/plot/prior.py +++ b/bofire/plot/prior.py @@ -1,4 +1,4 @@ -from typing import Dict +from typing import Dict, Optional import numpy as np import plotly.express as px @@ -12,7 +12,7 @@ def plot_prior_pdf_plotly( prior: AnyPrior, lower: float, upper: float, - layout_options: Dict = {}, + layout_options: Optional[Dict] = None, ): """Plot the probability density function of the prior with plotly. @@ -33,7 +33,7 @@ def plot_prior_pdf_plotly( y=np.exp(priors.map(prior).log_prob(torch.from_numpy(x)).numpy()), ) - if len(layout_options) > 0: + if layout_options is not None: fig.update_layout(layout_options) return fig diff --git a/bofire/strategies/doe/design.py b/bofire/strategies/doe/design.py index f91d8edec..d975a993d 100644 --- a/bofire/strategies/doe/design.py +++ b/bofire/strategies/doe/design.py @@ -28,7 +28,7 @@ def find_local_max_ipopt( model_type: Union[str, Formula], n_experiments: Optional[int] = None, delta: float = 1e-7, - ipopt_options: Dict = {}, + ipopt_options: Optional[Dict] = None, sampling: Optional[pd.DataFrame] = None, fixed_experiments: Optional[pd.DataFrame] = None, objective: OptimalityCriterionEnum = OptimalityCriterionEnum.D_OPTIMALITY, @@ -41,7 +41,7 @@ def find_local_max_ipopt( n_experiments (int): Number of experiments. By default the value corresponds to the number of model terms - dimension of ker() + 3. delta (float): Regularization parameter. Default value is 1e-3. - ipopt_options (Dict): options for IPOPT. For more information see [this link](https://coin-or.github.io/Ipopt/OPTIONS.html) + ipopt_options (Dict, optional): options for IPOPT. For more information see [this link](https://coin-or.github.io/Ipopt/OPTIONS.html) sampling (Sampling, np.ndarray): Sampling class or a np.ndarray object containing the initial guess. fixed_experiments (pd.DataFrame): dataframe containing experiments that will be definitely part of the design. Values are set before the optimization. @@ -76,11 +76,9 @@ def find_local_max_ipopt( # check that NChooseK constraints only impose an upper bound on the number of nonzero components (and no lower bound) assert all( - [ - c.min_count == 0 - for c in domain.constraints - if isinstance(c, NChooseKConstraint) - ] + c.min_count == 0 + for c in domain.constraints + if isinstance(c, NChooseKConstraint) ), "NChooseKConstraint with min_count !=0 is not supported!" # determine number of experiments (only relevant if n_experiments is not provided by the user) @@ -140,6 +138,8 @@ def find_local_max_ipopt( x0[i] = val # set ipopt options + if ipopt_options is None: + ipopt_options = {} _ipopt_options = {"maxiter": 500, "disp": 0} for key in ipopt_options.keys(): _ipopt_options[key] = ipopt_options[key] diff --git a/bofire/strategies/doe/utils.py b/bofire/strategies/doe/utils.py index 5bbfc55a3..3e554f143 100644 --- a/bofire/strategies/doe/utils.py +++ b/bofire/strategies/doe/utils.py @@ -474,7 +474,7 @@ def nchoosek_constraints_as_bounds( ] # find and shuffle all combinations of elements of ind of length max_active - ind = np.array([c for c in combinations(ind, r=n_inactive)]) + ind = np.array(list(combinations(ind, r=n_inactive))) np.random.shuffle(ind) # set bounds to zero in each experiments for the variables that should be inactive diff --git a/bofire/surrogates/cloudpickle_module.py b/bofire/surrogates/cloudpickle_module.py index 347dec094..1db118dc4 100644 --- a/bofire/surrogates/cloudpickle_module.py +++ b/bofire/surrogates/cloudpickle_module.py @@ -5,8 +5,8 @@ try: from pickle import Unpickler # noqa: F401 - from cloudpickle import CloudPickler as Pickler # noqa: F401 from cloudpickle import * # noqa: F401, F403, + from cloudpickle import CloudPickler as Pickler # noqa: F401 except ModuleNotFoundError: warnings.warn("Cloudpicke is not available.") diff --git a/bofire/surrogates/diagnostics.py b/bofire/surrogates/diagnostics.py index 80f21e269..7b4b12a39 100644 --- a/bofire/surrogates/diagnostics.py +++ b/bofire/surrogates/diagnostics.py @@ -293,9 +293,9 @@ def validate_results(cls, v, values): ) # check columns of X if v[0].X is not None: - cols = sorted(list(v[0].X.columns)) + cols = sorted(v[0].X.columns) for i in v: - if sorted(list(i.X.columns)) != cols: + if sorted(i.X.columns) != cols: raise ValueError("Columns of X do not match.") return v diff --git a/bofire/surrogates/mlp.py b/bofire/surrogates/mlp.py index 7d5386a67..a0e178ddd 100644 --- a/bofire/surrogates/mlp.py +++ b/bofire/surrogates/mlp.py @@ -132,7 +132,7 @@ def fit_mlp( optimizer = torch.optim.Adam(mlp.parameters(), lr=lr, weight_decay=weight_decay) for _ in range(n_epoches): current_loss = 0.0 - for i, data in enumerate(train_loader, 0): + for data in train_loader: # Get and prepare inputs inputs, targets = data if len(targets.shape) == 1: @@ -181,7 +181,7 @@ def _fit(self, X: pd.DataFrame, Y: pd.DataFrame): mlps = [] subsample_size = round(self.subsample_fraction * X.shape[0]) - for i in range(self.n_estimators): + for _ in range(self.n_estimators): # resample X and Y sample_idx = np.random.choice(X.shape[0], replace=True, size=subsample_size) tX = torch.from_numpy(transformed_X.values[sample_idx]).to(**tkwargs) diff --git a/bofire/surrogates/surrogate.py b/bofire/surrogates/surrogate.py index 294a937b8..e311caf63 100644 --- a/bofire/surrogates/surrogate.py +++ b/bofire/surrogates/surrogate.py @@ -59,7 +59,7 @@ def validate_predictions(self, predictions: pd.DataFrame) -> pd.DataFrame: expected_cols = [ f"{key}_{t}" for key in self.outputs.get_keys() for t in ["pred", "sd"] ] - if sorted(list(predictions.columns)) != sorted(expected_cols): + if sorted(predictions.columns) != sorted(expected_cols): raise ValueError( f"Predictions are ill-formatted. Expected: {expected_cols}, got: {list(predictions.columns)}." ) diff --git a/bofire/surrogates/trainable.py b/bofire/surrogates/trainable.py index 665fa0d3c..f3cf91a20 100644 --- a/bofire/surrogates/trainable.py +++ b/bofire/surrogates/trainable.py @@ -52,20 +52,22 @@ def cross_validate( folds: int = -1, include_X: bool = False, include_labcodes: bool = False, - hooks: Dict[ - str, - Callable[ - [ - Surrogate, - pd.DataFrame, - pd.DataFrame, - pd.DataFrame, - pd.DataFrame, + hooks: Optional[ + Dict[ + str, + Callable[ + [ + Surrogate, + pd.DataFrame, + pd.DataFrame, + pd.DataFrame, + pd.DataFrame, + ], + Any, ], - Any, - ], - ] = {}, - hook_kwargs: Dict[str, Dict[str, Any]] = {}, + ] + ] = None, + hook_kwargs: Optional[Dict[str, Dict[str, Any]]] = None, ) -> Tuple[CvResults, CvResults, Dict[str, List[Any]]]: """Perform a cross validation for the provided training data. @@ -103,6 +105,10 @@ def cross_validate( elif folds == -1: folds = n # preprocess hooks + if hooks is None: + hooks = {} + if hook_kwargs is None: + hook_kwargs = {} hook_results = {key: [] for key in hooks.keys()} # instantiate kfold object cv = KFold(n_splits=folds, shuffle=True) diff --git a/bofire/utils/doe.py b/bofire/utils/doe.py index e0072aa74..a052d22e0 100644 --- a/bofire/utils/doe.py +++ b/bofire/utils/doe.py @@ -1,6 +1,6 @@ import itertools import warnings -from typing import List +from typing import List, Optional import pandas as pd from sklearn.preprocessing import MinMaxScaler @@ -12,8 +12,8 @@ def get_confounding_matrix( inputs: Inputs, design: pd.DataFrame, - powers: List[int] = [], - interactions: List[int] = [2], + powers: Optional[List[int]] = None, + interactions: Optional[List[int]] = None, ): """Analyzes the confounding of a design and returns the confounding matrix. @@ -39,16 +39,22 @@ def get_confounding_matrix( data=scaler.fit_transform(design[keys]), columns=keys, ) + # add powers - for p in powers: - assert p > 1, "Power has to be at least of degree two." - for key in keys: - scaled_design[f"{key}**{p}"] = scaled_design[key] ** p + if powers is not None: + for p in powers: + assert p > 1, "Power has to be at least of degree two." + for key in keys: + scaled_design[f"{key}**{p}"] = scaled_design[key] ** p # add interactions + if interactions is None: + interactions = [2] + for i in interactions: assert i > 1, "Interaction has to be at least of degree two." assert i < len(keys) + 1, f"Interaction has to be smaller than {len(keys)+1}." for combi in itertools.combinations(keys, i): scaled_design[":".join(combi)] = scaled_design[list(combi)].prod(axis=1) + return scaled_design.corr() diff --git a/bofire/utils/reduce.py b/bofire/utils/reduce.py index d6659df3f..138b27148 100644 --- a/bofire/utils/reduce.py +++ b/bofire/utils/reduce.py @@ -291,7 +291,7 @@ def remove_eliminated_inputs(domain: Domain, transform: AffineTransform) -> Doma # build up dict from domain.equalities e.g. {"xi1": [coeff(xj1), ..., coeff(xjn)], ... "xik":...} coeffs_dict = {} - for i, e in enumerate(transform.equalities): + for e in transform.equalities: coeffs = np.zeros(M + 1) for j, name in enumerate(e[1]): coeffs[inputs_dict[name]] = e[2][j] diff --git a/bofire/utils/torch_tools.py b/bofire/utils/torch_tools.py index 6fb6e44d6..d3bb2e825 100644 --- a/bofire/utils/torch_tools.py +++ b/bofire/utils/torch_tools.py @@ -349,7 +349,7 @@ def objective(samples: Tensor, X: Optional[Tensor] = None) -> Tensor: def get_initial_conditions_generator( strategy: Strategy, transform_specs: Dict, - ask_options: Dict = {}, + ask_options: Optional[Dict] = None, sequential: bool = True, ) -> Callable[[int, int, int], Tensor]: """Takes a strategy object and returns a callable which uses this @@ -370,6 +370,8 @@ def get_initial_conditions_generator( Callable[[int, int, int], Tensor]: Callable that can be passed to `batch_initial_conditions`. """ + if ask_options is None: + ask_options = {} def generator(n: int, q: int, seed: int) -> Tensor: if sequential: diff --git a/pyproject.toml b/pyproject.toml index 9c0c6bdae..b199839ca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,3 +5,18 @@ build-backend = "setuptools.build_meta" [tool.setuptools_scm] local_scheme = "node-and-date" write_to = "./bofire/version.py" +[tool.ruff] +ignore = [ + "E501", # don't enforce for comments and docstrings + "B017", # required for tests + "B027", # required for optional _tell method + "B023", + "B028", + "B904", + "B905" +] +line-length = 88 +select = ["B", "C", "E", "F", "W", "I"] + +[tool.ruff.mccabe] +max-complexity = 18 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index b707548a3..000000000 --- a/setup.cfg +++ /dev/null @@ -1,16 +0,0 @@ -[isort] -multi_line_output=3 -include_trailing_comma=True -force_grid_wrap=0 -use_parentheses=True -line_length=88 - -[flake8] -ignore = E203, E266, E501, W503 -max-line-length = 88 -max-complexity = 18 -select = B,C,E,F,W,T4 - -[mypy] -files=bofire -ignore_missing_imports=true \ No newline at end of file diff --git a/tests/bofire/data_models/specs/strategies.py b/tests/bofire/data_models/specs/strategies.py index 95ad91d66..b79b73bc7 100644 --- a/tests/bofire/data_models/specs/strategies.py +++ b/tests/bofire/data_models/specs/strategies.py @@ -104,8 +104,6 @@ "max_iters": 1000, "num_base_samples": 1000, "sampling_method": SamplingMethodEnum.UNIFORM, - "num_base_samples": 1000, - "max_iters": 1000, "seed": 42, }, ) diff --git a/tests/bofire/data_models/test_constraint_fulfillment.py b/tests/bofire/data_models/test_constraint_fulfillment.py index 1efea90ca..48c48fac3 100644 --- a/tests/bofire/data_models/test_constraint_fulfillment.py +++ b/tests/bofire/data_models/test_constraint_fulfillment.py @@ -19,7 +19,7 @@ def get_row(features, value: float = None, values: List[float] = None): if values is None: values = [value for _ in range(len(features))] - return pd.DataFrame.from_dict([{f: v for f, v in zip(features, values)}]) + return pd.DataFrame.from_dict([dict(zip(features, values))]) @pytest.mark.parametrize( diff --git a/tests/bofire/data_models/test_features.py b/tests/bofire/data_models/test_features.py index 903035ced..925b56750 100644 --- a/tests/bofire/data_models/test_features.py +++ b/tests/bofire/data_models/test_features.py @@ -1077,7 +1077,7 @@ def test_categorical_descriptor_input_feature_from_dataframe( categories, descriptors, values ): df = pd.DataFrame.from_dict( - {category: v for category, v in zip(categories, values)}, + dict(zip(categories, values)), orient="index", columns=descriptors, ) @@ -1115,7 +1115,7 @@ def test_categorical_descriptor_input_feature_from_dataframe( ], ) def test_feature_sorting(unsorted_list, sorted_list): - assert list(sorted(unsorted_list)) == sorted_list + assert sorted(unsorted_list) == sorted_list # test features container diff --git a/tests/bofire/strategies/doe/test_design.py b/tests/bofire/strategies/doe/test_design.py index 15d12312d..80355367d 100644 --- a/tests/bofire/strategies/doe/test_design.py +++ b/tests/bofire/strategies/doe/test_design.py @@ -151,9 +151,9 @@ def test_find_local_max_ipopt_mixed_results(): A = find_local_max_ipopt(domain, "fully-quadratic", ipopt_options={"maxiter": 100}) opt = np.eye(3) for row in A.to_numpy(): - assert any([np.allclose(row, o, atol=1e-2) for o in opt]) + assert any(np.allclose(row, o, atol=1e-2) for o in opt) for o in opt: - assert any([np.allclose(o, row, atol=1e-2) for row in A.to_numpy()]) + assert any(np.allclose(o, row, atol=1e-2) for row in A.to_numpy()) @pytest.mark.skipif(not CYIPOPT_AVAILABLE, reason="requires cyipopt") @@ -186,9 +186,9 @@ def test_find_local_max_ipopt_results(): A = find_local_max_ipopt(domain, "linear", n_experiments=12) opt = np.array([[0.2, 0.2, 0.6], [0.3, 0.6, 0.1], [0.7, 0.1, 0.2], [0.3, 0.1, 0.6]]) for row in A.to_numpy(): - assert any([np.allclose(row, o, atol=1e-2) for o in opt]) + assert any(np.allclose(row, o, atol=1e-2) for o in opt) for o in opt[:-1]: - assert any([np.allclose(o, row, atol=1e-2) for row in A.to_numpy()]) + assert any(np.allclose(o, row, atol=1e-2) for row in A.to_numpy()) # def test_find_local_max_ipopt_sampling(): @@ -310,9 +310,9 @@ def test_find_local_max_ipopt_fixed_experiments(): ) opt = np.eye(3) for row in A.to_numpy(): - assert any([np.allclose(row, o, atol=1e-2) for o in opt]) + assert any(np.allclose(row, o, atol=1e-2) for o in opt) for o in opt: - assert any([np.allclose(o, row, atol=1e-2) for row in A.to_numpy()]) + assert any(np.allclose(o, row, atol=1e-2) for row in A.to_numpy()) assert np.allclose(A.to_numpy()[:2, :], opt[:2, :]) diff --git a/tests/bofire/strategies/test_base.py b/tests/bofire/strategies/test_base.py index 34ea9f789..21b52e91b 100644 --- a/tests/bofire/strategies/test_base.py +++ b/tests/bofire/strategies/test_base.py @@ -287,7 +287,7 @@ def _get_acqfs( ] -@pytest.mark.parametrize("domain", [(domain) for domain in domains]) +@pytest.mark.parametrize("domain", list(domains)) def test_base_create(domain: Domain): with pytest.raises(ValueError, match="number sobol samples"): DummyStrategyDataModel(domain=domain, num_sobol_samples=5) diff --git a/tests/bofire/strategies/test_doe.py b/tests/bofire/strategies/test_doe.py index 6eb9c0a9d..213b7e2fd 100644 --- a/tests/bofire/strategies/test_doe.py +++ b/tests/bofire/strategies/test_doe.py @@ -154,9 +154,9 @@ def test_doe_strategy_correctness(): [[0.2, 0.2, 0.6], [0.3, 0.6, 0.1], [0.7, 0.1, 0.2], [0.3, 0.1, 0.6]] ) for row in candidates.to_numpy(): - assert any([np.allclose(row, o, atol=1e-2) for o in candidates_expected]) + assert any(np.allclose(row, o, atol=1e-2) for o in candidates_expected) for o in candidates_expected[:-1]: - assert any([np.allclose(o, row, atol=1e-2) for row in candidates.to_numpy()]) + assert any(np.allclose(o, row, atol=1e-2) for row in candidates.to_numpy()) def test_doe_strategy_amount_of_candidates(): diff --git a/tests/bofire/strategies/test_qparego.py b/tests/bofire/strategies/test_qparego.py index 795a73aa7..c51eb4779 100644 --- a/tests/bofire/strategies/test_qparego.py +++ b/tests/bofire/strategies/test_qparego.py @@ -99,7 +99,7 @@ def test_invalid_qparego_init_domain(domain): @pytest.mark.parametrize( "num_test_candidates", - [num_test_candidates for num_test_candidates in range(1, 2)], + list(range(1, 2)), ) def test_qparego(num_test_candidates): # generate data @@ -124,7 +124,7 @@ def test_qparego(num_test_candidates): @pytest.mark.parametrize( "num_test_candidates", - [num_test_candidates for num_test_candidates in range(1, 2)], + list(range(1, 2)), ) def test_qparego_constraints(num_test_candidates): # generate data diff --git a/tests/bofire/strategies/test_strategy.py b/tests/bofire/strategies/test_strategy.py index b4e1e8c3e..808a44407 100644 --- a/tests/bofire/strategies/test_strategy.py +++ b/tests/bofire/strategies/test_strategy.py @@ -521,7 +521,7 @@ def test_predictive_strategy_predict(domain, experiments): ) strategy.tell(experiments) preds = strategy.predict(generate_candidates(domain=domain)) - assert sorted(list(preds.columns)) == sorted( + assert sorted(preds.columns) == sorted( [ "of1_pred", "of2_pred", diff --git a/tests/bofire/surrogates/test_feature_importance.py b/tests/bofire/surrogates/test_feature_importance.py index 72c26849a..b1d77c288 100644 --- a/tests/bofire/surrogates/test_feature_importance.py +++ b/tests/bofire/surrogates/test_feature_importance.py @@ -91,5 +91,5 @@ def test_combine_permutation_importances(n_folds): importance = combine_permutation_importances( importances=pi["pemutation_importance"], metric=m ) - list(importance.columns) == model.inputs.get_keys() + assert list(importance.columns) == model.inputs.get_keys() assert len(importance) == n_folds