Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix division-by-zero while initializing CMAES #86

Merged
merged 1 commit into from
Oct 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/evotorch/algorithms/cmaes.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
This namespace contains the CMAES class
"""

from typing import Optional, Tuple
from typing import Optional, Tuple, Union

import numpy as np
import torch
Expand Down Expand Up @@ -80,6 +80,13 @@ def _limit_stdev(sigma: torch.Tensor, C: torch.Tensor, stdev_min: Optional[float
return C


def _safe_divide(a: Union[Real, torch.Tensor], b: Union[Real, torch.Tensor]) -> Union[torch.Tensor]:
tolerance = 1e-8
if abs(b) < tolerance:
b = (-tolerance) if b < 0 else tolerance
return a / b


class CMAES(SearchAlgorithm, SinglePopulationAlgorithmMixin):
"""
CMAES: Covariance Matrix Adaptation Evolution Strategy.
Expand Down Expand Up @@ -360,9 +367,11 @@ def __init__(
# Note that we could use the exact formulation with Gamma functions, but we'll retain this form for consistency
self.unbiased_expectation = np.sqrt(d) * (1 - (1 / (4 * d)) + 1 / (21 * d**2))

self.last_ex = None

# How often to decompose C
if limit_C_decomposition:
self.decompose_C_freq = max(1, int(1 / np.floor(10 * d * (self.c_1.cpu() + self.c_mu.cpu()))))
self.decompose_C_freq = max(1, int(np.floor(_safe_divide(1, 10 * d * (self.c_1.cpu() + self.c_mu.cpu())))))
else:
self.decompose_C_freq = 1

Expand Down