Skip to content

Commit 878d847

Browse files
authored
Merge pull request #216 from CyberAgentAILab/migrate-to-ruff
Migrate to ruff from black/isort/flake8
2 parents a878de7 + b670b5e commit 878d847

34 files changed

Lines changed: 264 additions & 568 deletions

.github/workflows/examples.yml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ jobs:
1212
runs-on: ubuntu-latest
1313
strategy:
1414
matrix:
15-
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
15+
python-version: ["3.9", "3.14"]
1616
steps:
17-
- uses: actions/checkout@v4
17+
- uses: actions/checkout@v6
1818
- name: Set up Python ${{ matrix.python-version }}
19-
uses: actions/setup-python@v5
19+
uses: actions/setup-python@v6
2020
with:
2121
python-version: ${{ matrix.python-version }}
2222
architecture: x64
@@ -39,9 +39,9 @@ jobs:
3939
examples-cmawm-without-scipy:
4040
runs-on: ubuntu-latest
4141
steps:
42-
- uses: actions/checkout@v4
42+
- uses: actions/checkout@v6
4343
- name: Set up Python
44-
uses: actions/setup-python@v5
44+
uses: actions/setup-python@v6
4545
with:
4646
python-version: '3.x'
4747
architecture: x64

.github/workflows/tests.yml

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,28 +11,28 @@ jobs:
1111
lint:
1212
runs-on: ubuntu-latest
1313
steps:
14-
- uses: actions/checkout@v4
14+
- uses: actions/checkout@v6
1515
- name: Set up Python
16-
uses: actions/setup-python@v5
16+
uses: actions/setup-python@v6
1717
with:
1818
python-version: '3.x'
1919
architecture: x64
2020
- name: Install dependencies
2121
run: |
2222
python -m pip install --upgrade pip setuptools
23-
pip install --progress-bar off numpy matplotlib scipy mypy flake8 black torch gpytorch
24-
- run: flake8 . --show-source --statistics
25-
- run: black --check .
23+
pip install --progress-bar off numpy matplotlib scipy mypy ruff torch gpytorch
24+
- run: ruff check .
25+
- run: ruff format --check .
2626
- run: mypy cmaes
2727
test:
2828
runs-on: ubuntu-latest
2929
strategy:
3030
matrix:
3131
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"]
3232
steps:
33-
- uses: actions/checkout@v4
33+
- uses: actions/checkout@v6
3434
- name: Setup Python${{ matrix.python-version }}
35-
uses: actions/setup-python@v5
35+
uses: actions/setup-python@v6
3636
with:
3737
python-version: ${{ matrix.python-version }}
3838
architecture: x64
@@ -44,9 +44,9 @@ jobs:
4444
test-numpy2:
4545
runs-on: ubuntu-latest
4646
steps:
47-
- uses: actions/checkout@v4
47+
- uses: actions/checkout@v6
4848
- name: Setup Python
49-
uses: actions/setup-python@v5
49+
uses: actions/setup-python@v6
5050
with:
5151
architecture: x64
5252
- name: Install dependencies

benchmark/optuna_solver.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@
1616
"sampler",
1717
choices=["cmaes", "sep-cmaes", "ipop-cmaes", "ipop-sep-cmaes", "pycma", "ws-cmaes"],
1818
)
19-
parser.add_argument(
20-
"--loglevel", choices=["debug", "info", "warning", "error"], default="warning"
21-
)
19+
parser.add_argument("--loglevel", choices=["debug", "info", "warning", "error"], default="warning")
2220
parser.add_argument("--warm-starting-trials", type=int, default=0)
2321
args = parser.parse_args()
2422

@@ -93,9 +91,7 @@ def sample_relative(
9391
return self._sampler.sample_relative(study, trial, search_space)
9492

9593
def sample_independent(self, study, trial, param_name, param_distribution):
96-
return self._sampler.sample_independent(
97-
study, trial, param_name, param_distribution
98-
)
94+
return self._sampler.sample_independent(study, trial, param_name, param_distribution)
9995

10096
def after_trial(
10197
self,

benchmark/problem_himmelblau.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,15 @@ def __init__(self, params: List[Optional[float]]):
1212

1313
def evaluate(self, next_step: int) -> List[float]:
1414
self._current_step = 1
15-
value = (self._x1**2 + self._x2 - 11.0) ** 2 + (
16-
self._x1 + self._x2**2 - 7.0
17-
) ** 2
15+
value = (self._x1**2 + self._x2 - 11.0) ** 2 + (self._x1 + self._x2**2 - 7.0) ** 2
1816
return [value]
1917

2018
def current_step(self) -> int:
2119
return self._current_step
2220

2321

2422
class HimmelblauProblem(problem.Problem):
25-
def create_evaluator(
26-
self, params: List[Optional[float]]
27-
) -> Optional[problem.Evaluator]:
23+
def create_evaluator(self, params: List[Optional[float]]) -> Optional[problem.Evaluator]:
2824
return HimmelblauEvaluator(params)
2925

3026

benchmark/problem_rastrigin.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ def current_step(self) -> int:
2424

2525

2626
class RastriginProblem(problem.Problem):
27-
def create_evaluator(
28-
self, params: List[Optional[float]]
29-
) -> Optional[problem.Evaluator]:
27+
def create_evaluator(self, params: List[Optional[float]]) -> Optional[problem.Evaluator]:
3028
return RastriginEvaluator(params)
3129

3230

@@ -39,8 +37,7 @@ def create_problem(self, seed: int) -> Problem:
3937

4038
def specification(self) -> problem.ProblemSpec:
4139
params = [
42-
problem.Var(f"x{i + 1}", problem.ContinuousRange(-5.12, 5.12))
43-
for i in range(self.dim)
40+
problem.Var(f"x{i + 1}", problem.ContinuousRange(-5.12, 5.12)) for i in range(self.dim)
4441
]
4542
return problem.ProblemSpec(
4643
name=f"Rastrigin (dim={self.dim})",

benchmark/problem_rosenbrock.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ def current_step(self) -> int:
2424

2525

2626
class RosenbrockProblem(problem.Problem):
27-
def create_evaluator(
28-
self, params: List[Optional[float]]
29-
) -> Optional[problem.Evaluator]:
27+
def create_evaluator(self, params: List[Optional[float]]) -> Optional[problem.Evaluator]:
3028
return RosenbrockEvaluator(params)
3129

3230

benchmark/problem_six_hump_camel.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,7 @@ def current_step(self) -> int:
2828

2929

3030
class SixHumpCamelProblem(problem.Problem):
31-
def create_evaluator(
32-
self, params: List[Optional[float]]
33-
) -> Optional[problem.Evaluator]:
31+
def create_evaluator(self, params: List[Optional[float]]) -> Optional[problem.Evaluator]:
3432
return SixHumpCamelEvaluator(params)
3533

3634

benchmark/problem_sphere.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@ def current_step(self) -> int:
2525

2626

2727
class SphereProblem(problem.Problem):
28-
def create_evaluator(
29-
self, params: list[Optional[float]]
30-
) -> Optional[problem.Evaluator]:
28+
def create_evaluator(self, params: list[Optional[float]]) -> Optional[problem.Evaluator]:
3129
return SphereEvaluator(params)
3230

3331

@@ -40,8 +38,7 @@ def create_problem(self, seed: int) -> Problem:
4038

4139
def specification(self) -> problem.ProblemSpec:
4240
params = [
43-
problem.Var(f"x{i + 1}", problem.ContinuousRange(-5.12, 5.12))
44-
for i in range(self.dim)
41+
problem.Var(f"x{i + 1}", problem.ContinuousRange(-5.12, 5.12)) for i in range(self.dim)
4542
]
4643
return problem.ProblemSpec(
4744
name=f"Sphere (dim={self.dim})",

cmaes/_catcma.py

Lines changed: 20 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ def __init__(
9696
):
9797
assert sigma > 0, "sigma must be non-zero positive value"
9898

99-
assert np.all(
100-
np.abs(mean) < _MEAN_MAX
101-
), f"Abs of all elements of mean vector must be less than {_MEAN_MAX}"
99+
assert np.all(np.abs(mean) < _MEAN_MAX), (
100+
f"Abs of all elements of mean vector must be less than {_MEAN_MAX}"
101+
)
102102

103103
self._n_co = len(mean)
104104
self._n_ca = len(cat_num)
@@ -141,12 +141,8 @@ def __init__(
141141

142142
# learning rate for the cumulation for the step-size control
143143
c_sigma = (mu_eff + 2) / (self._n_co + mu_eff + 5)
144-
d_sigma = (
145-
1 + 2 * max(0, math.sqrt((mu_eff - 1) / (self._n_co + 1)) - 1) + c_sigma
146-
)
147-
assert (
148-
c_sigma < 1
149-
), "invalid learning rate for cumulation for the step-size control"
144+
d_sigma = 1 + 2 * max(0, math.sqrt((mu_eff - 1) / (self._n_co + 1)) - 1) + c_sigma
145+
assert c_sigma < 1, "invalid learning rate for cumulation for the step-size control"
150146

151147
# learning rate for cumulation for the rank-one update
152148
cc = (4 + mu_eff / self._n_co) / (self._n_co + 4 + 2 * mu_eff / self._n_co)
@@ -208,18 +204,16 @@ def __init__(
208204
"Parameters in categorical distribution with fewer categories "
209205
"must be zero-padded at the end"
210206
)
211-
assert np.all(
212-
(cat_param >= 0) & (cat_param <= 1)
213-
), "All elements in categorical distribution parameter must be between 0 and 1"
214-
assert np.allclose(
215-
np.sum(cat_param, axis=1), 1
216-
), "Each row in categorical distribution parameter must sum to 1"
207+
assert np.all((cat_param >= 0) & (cat_param <= 1)), (
208+
"All elements in categorical distribution parameter must be between 0 and 1"
209+
)
210+
assert np.allclose(np.sum(cat_param, axis=1), 1), (
211+
"Each row in categorical distribution parameter must sum to 1"
212+
)
217213
self._q = cat_param
218214

219215
self._q_min = (
220-
margin
221-
if margin is not None
222-
else (1 - 0.73 ** (1 / self._n_ca)) / (self._K - 1)
216+
margin if margin is not None else (1 - 0.73 ** (1 / self._n_ca)) / (self._K - 1)
223217
)
224218
self._min_eigenvalue = min_eigenvalue if min_eigenvalue is not None else 1e-30
225219

@@ -367,16 +361,14 @@ def _repair_infeasible_params(self, param: np.ndarray) -> np.ndarray:
367361
param = np.where(param > self._bounds[:, 1], self._bounds[:, 1], param)
368362
return param
369363

370-
def tell(
371-
self, solutions: list[tuple[tuple[np.ndarray, np.ndarray], float]]
372-
) -> None:
364+
def tell(self, solutions: list[tuple[tuple[np.ndarray, np.ndarray], float]]) -> None:
373365
"""Tell evaluation values"""
374366

375367
assert len(solutions) == self._popsize, "Must tell popsize-length solutions."
376368
for s in solutions:
377-
assert np.all(
378-
np.abs(s[0][0]) < _MEAN_MAX
379-
), f"Abs of all param values must be less than {_MEAN_MAX} to avoid overflow errors"
369+
assert np.all(np.abs(s[0][0]) < _MEAN_MAX), (
370+
f"Abs of all param values must be less than {_MEAN_MAX} to avoid overflow errors"
371+
)
380372

381373
self._g += 1
382374
solutions.sort(key=lambda s: s[1])
@@ -406,9 +398,7 @@ def tell(
406398
) * C_2.dot(y_w)
407399

408400
norm_p_sigma = np.linalg.norm(self._p_sigma)
409-
self._sigma *= np.exp(
410-
(self._c_sigma / self._d_sigma) * (norm_p_sigma / self._chi_n - 1)
411-
)
401+
self._sigma *= np.exp((self._c_sigma / self._d_sigma) * (norm_p_sigma / self._chi_n - 1))
412402
self._sigma = min(self._sigma, _SIGMA_MAX)
413403

414404
# Covariance matrix adaption
@@ -430,13 +420,7 @@ def tell(
430420
np.array([w * np.outer(y, y) for w, y in zip(self._weights, y_k)]), axis=0
431421
)
432422
self._C = (
433-
(
434-
1
435-
+ self._c1 * delta_h_sigma
436-
- self._c1
437-
- self._cmu * np.sum(self._weights)
438-
)
439-
* self._C
423+
(1 + self._c1 * delta_h_sigma - self._c1 - self._cmu * np.sum(self._weights)) * self._C
440424
+ self._c1 * rank_one
441425
+ self._cmu * rank_mu
442426
)
@@ -470,9 +454,7 @@ def tell(
470454
beta = self._delta / (self._param_sum**0.5)
471455
self._s = (1 - beta) * self._s + np.sqrt(beta * (2 - beta)) * ngrad_sqF / pnorm
472456
self._gamma = (1 - beta) ** 2 * self._gamma + beta * (2 - beta)
473-
self._Delta *= np.exp(
474-
beta * (self._gamma - np.dot(self._s, self._s) / self._alpha)
475-
)
457+
self._Delta *= np.exp(beta * (self._gamma - np.dot(self._s, self._s) / self._alpha))
476458
self._Delta = min(self._Delta, self._Delta_max)
477459

478460
# Margin Correction
@@ -490,8 +472,7 @@ def should_stop(self) -> bool:
490472
# Stop if the range of function values of the recent generation is below tolfun.
491473
if (
492474
self.generation > self._funhist_term
493-
and np.max(self._funhist_values) - np.min(self._funhist_values)
494-
< self._tolfun
475+
and np.max(self._funhist_values) - np.min(self._funhist_values) < self._tolfun
495476
):
496477
return True
497478

0 commit comments

Comments
 (0)