Skip to content

Commit 0894a50

Browse files
authored
152 ruff apply unsafe code fixes for code basis (#153)
1 parent 1ea5e02 commit 0894a50

18 files changed

+52
-42
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ physchem_matrix
122122
# [88.065, 20.23 , 1. ]])
123123
```
124124

125-
MolPipeline provides further features and descriptors from RDKit,
125+
MolPipeline provides further features and descriptors from RDKit,
126126
for example Morgan (binary/count) fingerprints and MACCS keys.
127127
See the [04_feature_calculation notebook](notebooks/04_feature_calculation.ipynb) for more examples.
128128

molpipeline/estimators/chemprop/component_wrapper.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,7 @@
3131
from chemprop.nn.predictors import MveFFN as _MveFFN
3232
from chemprop.nn.predictors import RegressionFFN as _RegressionFFN
3333
from chemprop.nn.predictors import SpectralFFN as _SpectralFFN
34-
from chemprop.nn.predictors import (
35-
_FFNPredictorBase as _Predictor, # pylint: disable=protected-access
36-
)
34+
from chemprop.nn.predictors import _FFNPredictorBase as _Predictor
3735
from chemprop.nn.transforms import UnscaleTransform
3836
from chemprop.nn.utils import Activation, get_activation_function
3937
from sklearn.base import BaseEstimator
@@ -477,7 +475,7 @@ def reinitialize_network(self) -> Self:
477475
# pylint: disable=protected-access
478476
self.metrics = [self.predictor._T_default_metric, self.criterion]
479477
else:
480-
self.metrics = list(self.metric_list) + [self.criterion]
478+
self.metrics = [*list(self.metric_list), self.criterion]
481479

482480
return self
483481

molpipeline/estimators/chemprop/featurizer_wrapper/graph_wrapper.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ class SimpleMoleculeMolGraphFeaturizer(_SimpleMoleculeMolGraphFeaturizer):
2020
extra_bond_fdim: InitVar[int]
2121

2222
def get_params(
23-
self, deep: bool = True # pylint: disable=unused-argument
23+
self,
24+
deep: bool = True, # pylint: disable=unused-argument
2425
) -> dict[str, InitVar[int]]:
2526
"""Get parameters for the featurizer.
2627

molpipeline/estimators/chemprop/models.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,8 @@ def __sklearn_tags__(self) -> Tags:
149149
return tags
150150

151151
def _predict(
152-
self, X: MoleculeDataset # pylint: disable=invalid-name
152+
self,
153+
X: MoleculeDataset, # pylint: disable=invalid-name
153154
) -> npt.NDArray[np.float64]:
154155
"""Predict the labels.
155156
@@ -207,7 +208,8 @@ def fit(
207208
return super().fit(X, y)
208209

209210
def predict(
210-
self, X: MoleculeDataset # pylint: disable=invalid-name
211+
self,
212+
X: MoleculeDataset, # pylint: disable=invalid-name
211213
) -> npt.NDArray[np.float64]:
212214
"""Predict the output.
213215
@@ -234,7 +236,8 @@ def predict(
234236

235237
@available_if(_is_classifier)
236238
def predict_proba(
237-
self, X: MoleculeDataset # pylint: disable=invalid-name
239+
self,
240+
X: MoleculeDataset, # pylint: disable=invalid-name
238241
) -> npt.NDArray[np.float64]:
239242
"""Predict the probabilities.
240243

molpipeline/estimators/chemprop/neural_fingerprint.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ def fit(
8585
return super().fit(X, y)
8686

8787
def transform(
88-
self, X: MoleculeDataset # pylint: disable=invalid-name
88+
self,
89+
X: MoleculeDataset, # pylint: disable=invalid-name
8990
) -> npt.NDArray[np.float64]:
9091
"""Transform the input.
9192

molpipeline/estimators/similarity_transformation.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from typing import Any
66

77
try:
8-
from typing import Self # pylint: disable=no-name-in-module
8+
from typing import Self
99
except ImportError:
1010
from typing_extensions import Self
1111

@@ -92,7 +92,8 @@ def fit(
9292
return self
9393

9494
def transform(
95-
self, X: npt.NDArray[np.float64] | csr_matrix # pylint: disable=invalid-name
95+
self,
96+
X: npt.NDArray[np.float64] | csr_matrix, # pylint: disable=invalid-name
9697
) -> npt.NDArray[np.float64]:
9798
"""Transform the data.
9899
@@ -112,7 +113,7 @@ def transform(
112113

113114
def fit_transform(
114115
self,
115-
X: npt.NDArray[np.float64] | csr_matrix, # pylint: disable=invalid-name
116+
X: npt.NDArray[np.float64] | csr_matrix,
116117
y: npt.NDArray[np.float64] | None = None,
117118
**fit_params: Any,
118119
) -> npt.NDArray[np.float64]:

molpipeline/experimental/explainability/explainer.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,9 @@ class AbstractSHAPExplainer(abc.ABC): # pylint: disable=too-few-public-methods
162162

163163
@abc.abstractmethod
164164
def explain(
165-
self, X: Any, **kwargs: Any # pylint: disable=invalid-name
165+
self,
166+
X: Any, # pylint: disable=invalid-name
167+
**kwargs: Any,
166168
) -> list[SHAPFeatureExplanation | SHAPFeatureAndAtomExplanation]:
167169
"""Explain the predictions for the input data.
168170
@@ -282,7 +284,6 @@ def explain(
282284
SHAPFeatureExplanation | SHAPFeatureAndAtomExplanation
283285
] = []
284286
for input_sample in X:
285-
286287
input_sample = [input_sample]
287288

288289
# get predictions

molpipeline/experimental/explainability/visualization/visualization.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ def _add_shap_present_absent_features_text(
358358
)
359359

360360
delta = 0.05
361-
offset = offset + 0.0165
361+
offset += 0.0165
362362
fig.text(offset, 0.13, "prediction =", ha="center", fontsize=10)
363363
fig.text(
364364
offset + 2 * delta,
@@ -558,7 +558,6 @@ def structure_heatmap_shap( # pylint: disable=too-many-locals
558558
)
559559

560560
with plt.ioff():
561-
562561
drawer, _, _, normalizer, color_map = _structure_heatmap(
563562
explanation.molecule,
564563
explanation.atom_weights,

molpipeline/metrics/ignore_error_scorer.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import pandas as pd
1010
from loguru import logger
1111
from sklearn import metrics
12-
from sklearn.metrics._scorer import _BaseScorer # pylint: disable=protected-access
12+
from sklearn.metrics._scorer import _BaseScorer
1313

1414

1515
def ignored_value_scorer(
@@ -80,10 +80,10 @@ def newscore(
8080
)
8181
y_true_ = np.copy(np.array(y_true)[all_retained])
8282
y_pred_ = np.array(np.array(y_pred)[all_retained].tolist())
83-
_kwargs = dict(kwargs)
84-
if "sample_weight" in _kwargs and _kwargs["sample_weight"] is not None:
85-
_kwargs["sample_weight"] = _kwargs["sample_weight"][all_retained]
86-
return score_func(y_true_, y_pred_, **_kwargs)
83+
kwargs_ = dict(kwargs)
84+
if "sample_weight" in kwargs_ and kwargs_["sample_weight"] is not None:
85+
kwargs_["sample_weight"] = kwargs_["sample_weight"][all_retained]
86+
return score_func(y_true_, y_pred_, **kwargs_)
8787

8888
return metrics.make_scorer(
8989
newscore, response_method=response_method, **scorer_kwargs

molpipeline/mol2any/mol2chemprop.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
warnings.warn(
2323
"chemprop not installed. MolToChemprop will not work.",
2424
ImportWarning,
25+
stacklevel=2,
2526
)
2627

2728

molpipeline/mol2any/mol2rdkit_phys_chem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
# MolWt is removed as ExactMolWt is already included.
3333
# Ipc is removed because it causes trouble with numpy.
3434
DEFAULT_DESCRIPTORS = [
35-
name for name in RDKIT_DESCRIPTOR_DICT if name not in ["MolWt", "Ipc"]
35+
name for name in RDKIT_DESCRIPTOR_DICT if name not in {"MolWt", "Ipc"}
3636
]
3737

3838

molpipeline/mol2mol/reaction.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,9 @@ def pretransform_single(self, value: RDKitMol) -> OptionalMol:
157157
if len(product_list) > 1:
158158
if self.handle_multi == "warn":
159159
warnings.warn(
160-
"Not able to handle multiple reactions. An arbitrary reaction is selected."
160+
"Not able to handle multiple reactions. "
161+
"An arbitrary reaction is selected.",
162+
stacklevel=2,
161163
)
162164
elif self.handle_multi == "raise":
163165
if mol.HasProp("identifier"):

molpipeline/utils/json_operations.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,9 @@ def recursive_to_json(obj: Any) -> Any:
266266
# If the object is not a sklearn model, a warning is raised
267267
# as it might not be possible to recreate the object.
268268
warnings.warn(
269-
f"{type(obj)} has no get_params method. No parameters for initialization are retained."
269+
f"{type(obj)} has no get_params method. "
270+
f"No parameters for initialization are retained.",
271+
stacklevel=2,
270272
)
271273

272274
return object_dict

molpipeline/utils/multi_proc.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,15 @@ def check_available_cores(n_requested_cores: int) -> int:
2525
n_available_cores = multiprocessing.cpu_count()
2626
except ModuleNotFoundError:
2727
warnings.warn(
28-
"Cannot import multiprocessing library. Falling back to single core!"
28+
"Cannot import multiprocessing library. Falling back to single core!",
29+
stacklevel=2,
2930
)
3031
return 1
3132

3233
if n_requested_cores > n_available_cores:
3334
warnings.warn(
34-
"Requested more cores than available. Using maximum number of cores!"
35+
"Requested more cores than available. Using maximum number of cores!",
36+
stacklevel=2,
3537
)
3638
return n_available_cores
3739
if n_requested_cores < 0:

notebooks/02_scaffold_split_with_custom_estimators.ipynb

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -403,12 +403,9 @@
403403
"\n",
404404
" # setup the pipeline\n",
405405
" pipeline = Pipeline(\n",
406-
" [(\"auto2mol\", AutoToMol())]\n",
407-
" + [\n",
408-
" (\n",
409-
" \"morgan\",\n",
410-
" MolToMorganFP(n_bits=1024, radius=2),\n",
411-
" ),\n",
406+
" [\n",
407+
" (\"auto2mol\", AutoToMol()),\n",
408+
" (\"morgan\", MolToMorganFP(n_bits=1024, radius=2)),\n",
412409
" (\"RandomForestClassifier\", RandomForestClassifier(random_state=67056)),\n",
413410
" ]\n",
414411
" )\n",

notebooks/advanced_01_hyperopt_on_bbbp.ipynb

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,7 @@
786786
"\n",
787787
"# Let's pre-compute the molecular standardization\n",
788788
"pipeline_standardization = Pipeline(\n",
789-
" [(\"auto2mol\", AutoToMol())] + make_standardization_elements(),\n",
789+
" [(\"auto2mol\", AutoToMol()), *make_standardization_elements()],\n",
790790
" n_jobs=N_JOBS,\n",
791791
")\n",
792792
"\n",
@@ -897,9 +897,11 @@
897897
"for model_name, model_dict in estimator_dict.items():\n",
898898
"\n",
899899
" pipeline_estimator = Pipeline(\n",
900-
" [(\"auto2mol\", AutoToMol())]\n",
901-
" + [(\"morgan\", MolToMorganFP(return_as=\"dense\"))]\n",
902-
" + [(\"estimator\", model_dict[\"model\"])],\n",
900+
" [\n",
901+
" (\"auto2mol\", AutoToMol()),\n",
902+
" (\"morgan\", MolToMorganFP(return_as=\"dense\")),\n",
903+
" (\"estimator\", model_dict[\"model\"]),\n",
904+
" ],\n",
903905
" n_jobs=N_JOBS,\n",
904906
" )\n",
905907
"\n",
@@ -1021,7 +1023,7 @@
10211023
"source": [
10221024
"# pre-compute standardized molecules\n",
10231025
"pipeline_standardization = Pipeline(\n",
1024-
" [(\"auto2mol\", AutoToMol())] + make_standardization_elements(),\n",
1026+
" [(\"auto2mol\", AutoToMol()), *make_standardization_elements()],\n",
10251027
" n_jobs=N_JOBS,\n",
10261028
")\n",
10271029
"test_smiles_standardized = pipeline_standardization.transform(df_test[\"smiles\"])"

notebooks/advanced_02_add_custom_pipeline_elements.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@
195195
"\n",
196196
"\n",
197197
"class SimplifiedLogisticRegression(BaseEstimator, ClassifierMixin):\n",
198-
" \"\"\"Example estimator for the simplified logistic regression algorithm\"\"\"\n",
198+
" \"\"\"Example estimator for the simplified logistic regression algorithm.\"\"\"\n",
199199
"\n",
200200
" def __init__(self, lr=0.01, num_iter=10000):\n",
201201
" self.lr = lr\n",

notebooks/advanced_03_introduction_to_explainable_ai.ipynb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,12 +1078,12 @@
10781078
"# series_dict = {k:explanations_dict[k] for k in series_names}\n",
10791079
"series_dict = explanations_dict\n",
10801080
"\n",
1081-
"weight_min = min([exp.atom_weights.min() for exp in series_dict.values()])\n",
1082-
"weight_max = max([exp.atom_weights.max() for exp in series_dict.values()])\n",
1081+
"weight_min = min(exp.atom_weights.min() for exp in series_dict.values())\n",
1082+
"weight_max = max(exp.atom_weights.max() for exp in series_dict.values())\n",
10831083
"weight_abs_max = max(abs(weight_min), abs(weight_max))\n",
10841084
"# following Harren et al., we set the maximum color intensity to 70% of the maximal numerical value\n",
10851085
"# for better visual differentiations in low value regions.\n",
1086-
"weight_abs_max = weight_abs_max * 0.70"
1086+
"weight_abs_max *= 0.70"
10871087
]
10881088
},
10891089
{

0 commit comments

Comments
 (0)