Skip to content

Commit

Permalink
fix(opytimizer): Passes pre-commit through files.
Browse files Browse the repository at this point in the history
  • Loading branch information
gugarosa committed Sep 22, 2023
1 parent fd6b951 commit 7744b9b
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 46 deletions.
2 changes: 1 addition & 1 deletion examples/optimizers/science/create_sma.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
params = {"z": 0.03}

# Creates a WCA optimizer
o = SMA(params=params)
o = SMA(params=params)
2 changes: 1 addition & 1 deletion examples/optimizers/swarm/create_waoa.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from opytimizer.optimizers.swarm import WAOA

# Creates a WAOA optimizer
o = WAOA()
o = WAOA()
51 changes: 27 additions & 24 deletions opytimizer/optimizers/science/sma.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import numpy as np

import opytimizer.math.random as r
import opytimizer.utils.exception as e
import opytimizer.utils.constant as c
import opytimizer.utils.exception as e
from opytimizer.core import Optimizer
from opytimizer.core.agent import Agent
from opytimizer.core.function import Function
Expand Down Expand Up @@ -47,7 +47,7 @@ def __init__(self, params: Optional[Dict[str, Any]] = None) -> None:
self.build(params)

logger.info("Class overrided.")

@property
def z(self) -> float:
"""Probability threshold."""
Expand All @@ -62,7 +62,7 @@ def z(self, z: float) -> None:
raise e.ValueError("`z` should be >= 0")

self._z = z

@property
def weight(self) -> np.ndarray:
"""Array of weights."""
Expand All @@ -82,10 +82,8 @@ def compile(self, space: Space) -> None:
space: A Space object containing meta-information.
"""

self.weight = np.zeros(
(space.n_agents, space.n_variables, space.n_dimensions)
)

self.weight = np.zeros((space.n_agents, space.n_variables, space.n_dimensions))

def _update_weight(self, agents: List[Agent]):
"""Updates the weight of slime mould (eq. 2.5).
Expand All @@ -99,16 +97,19 @@ def _update_weight(self, agents: List[Agent]):
n_agents = len(agents)

for i in range(n_agents):

r1 = r.generate_uniform_random_number(0, 1,
(agents[i].n_variables, agents[i].n_dimensions))

if i <= int(n_agents/2):
self.weight[i] = 1 + r1 * \
np.log10((best - agents[i].fit)/((best - worst)+c.EPSILON) + 1)

r1 = r.generate_uniform_random_number(
0, 1, (agents[i].n_variables, agents[i].n_dimensions)
)

if i <= int(n_agents / 2):
self.weight[i] = 1 + r1 * np.log10(
(best - agents[i].fit) / ((best - worst) + c.EPSILON) + 1
)
else:
self.weight[i] = 1 - r1 * \
np.log10((best - agents[i].fit)/((best - worst)+c.EPSILON) + 1)
self.weight[i] = 1 - r1 * np.log10(
(best - agents[i].fit) / ((best - worst) + c.EPSILON) + 1
)

def update(self, space: Space, iteration: int, n_iterations: int) -> None:
"""Wraps Slime Mould Algorithm over all agents and variables.
Expand All @@ -123,13 +124,13 @@ def update(self, space: Space, iteration: int, n_iterations: int) -> None:

self._update_weight(space.agents)

a = np.arctanh(-((iteration+1)/(n_iterations+1)) + 1)
b = 1 - (iteration+1)/(n_iterations+1)
a = np.arctanh(-((iteration + 1) / (n_iterations + 1)) + 1)
b = 1 - (iteration + 1) / (n_iterations + 1)

for i, agent in enumerate(space.agents):

r2 = r.generate_uniform_random_number()

if r2 < self.z:
agent.fill_with_uniform()
else:
Expand All @@ -144,7 +145,9 @@ def update(self, space: Space, iteration: int, n_iterations: int) -> None:
l = r.generate_integer_random_number(
0, len(space.agents), exclude_value=k
)
agent.position = space.agents[0].position + vb * \
(self.weight[i] * (space.agents[k].position - space.agents[l].position))
agent.position = space.agents[0].position + vb * (
self.weight[i]
* (space.agents[k].position - space.agents[l].position)
)
else:
agent.position *= vc
agent.position *= vc
44 changes: 27 additions & 17 deletions opytimizer/optimizers/swarm/waoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@

import opytimizer.math.random as r
import opytimizer.utils.logging as l
from opytimizer.core.optimizer import Optimizer
from opytimizer.core.function import Function
from opytimizer.core.optimizer import Optimizer
from opytimizer.core.space import Space

logger = l.get_logger(__name__)


class WAOA(Optimizer):
"""A WAOA class, inherited from Optimizer.
This is the designed class to dife WAOA-related
This is the designed class to dife WAOA-related
variables and methods.
References:
Expand All @@ -33,13 +34,13 @@ def __init__(self, params: Optional[Dict[str, Any]] = None) -> None:
params (str): Contains key-value parameters to the meta-heuristics.
"""

logger.info('Overriding class: Optimizer -> SSA')
logger.info("Overriding class: Optimizer -> SSA")

super(WAOA, self).__init__()

self.build(params)

logger.info('Class overrided.')
logger.info("Class overrided.")

def update(self, space: Space, function: Function, iteration: int) -> None:
"""Wraps Walrus Optimization Algorithm over all agents and variables.
Expand All @@ -55,11 +56,13 @@ def update(self, space: Space, function: Function, iteration: int) -> None:
a = copy.deepcopy(agent)

for j in range(space.n_variables):

r1 = r.generate_integer_random_number(1, 2)
r2 = r.generate_uniform_random_number()

a.position[j] = agent.position[j] + r2 * (space.best_agent.position[j] - r1 * agent.position[j])
a.position[j] = agent.position[j] + r2 * (
space.best_agent.position[j] - r1 * agent.position[j]
)

a.clip_by_bound()

Expand All @@ -69,24 +72,28 @@ def update(self, space: Space, function: Function, iteration: int) -> None:
agent.fit = copy.deepcopy(a.fit)

k = r.generate_integer_random_number(0, space.n_agents, i)
if (space.agents[k].fit < agent.fit):

if space.agents[k].fit < agent.fit:

for j in range(space.n_variables):

r1 = r.generate_integer_random_number(1, 2)
r2 = r.generate_uniform_random_number()

a.position[j] = agent.position[j] + r2 * (space.agents[k].position[j] - r1 * agent.position[j])

a.position[j] = agent.position[j] + r2 * (
space.agents[k].position[j] - r1 * agent.position[j]
)

else:

for j in range(space.n_variables):

r2 = r.generate_uniform_random_number()

a.position[j] = agent.position[j] + r2 * (agent.position[j] - space.agents[k].position[j])

a.position[j] = agent.position[j] + r2 * (
agent.position[j] - space.agents[k].position[j]
)

a.clip_by_bound()

a.fit = function(a.position)
Expand All @@ -98,11 +105,14 @@ def update(self, space: Space, function: Function, iteration: int) -> None:

r2 = r.generate_uniform_random_number()

a.position[j] = agent.position[j] + ((agent.ub[j]/(iteration+1)) - r2 * (agent.lb[j]/(iteration+1)))
a.position[j] = agent.position[j] + (
(agent.ub[j] / (iteration + 1))
- r2 * (agent.lb[j] / (iteration + 1))
)

a.clip_by_bound()

a.fit = function(a.position)
if a.fit < agent.fit:
agent.position = copy.deepcopy(a.position)
agent.fit = copy.deepcopy(a.fit)
agent.fit = copy.deepcopy(a.fit)
11 changes: 8 additions & 3 deletions tests/opytimizer/optimizers/science/test_sma.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,31 @@
from opytimizer.optimizers.science import sma
from opytimizer.spaces import search


def test_sma_params():
params = {"z": 0.03}

new_sma = sma.SMA(params=params)

assert new_sma.z == 0.03


def test_sma_params_setter():
new_sma = sma.SMA()

try:
new_sma.z = "a"
except:
new_sma.z = 0.05

try:
new_sma.z = -1
except:
new_sma.z = 0.05

assert new_sma.z == 0.05


def test_sma_compile():
search_space = search.SearchSpace(
n_agents=2, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]
Expand All @@ -40,6 +43,7 @@ def test_sma_compile():

assert new_sma.weight == np.array([1])


def test_sma_update_weight():
def square(x):
return np.sum(x**2)
Expand All @@ -53,6 +57,7 @@ def square(x):

new_sma._update_weight(search_space.agents)


def test_sma_update():
search_space = search.SearchSpace(
n_agents=10, n_variables=2, lower_bound=[0, 0], upper_bound=[10, 10]
Expand All @@ -61,4 +66,4 @@ def test_sma_update():
new_sma = sma.SMA()
new_sma.compile(search_space)

new_sma.update(search_space, 1, 10)
new_sma.update(search_space, 1, 10)

0 comments on commit 7744b9b

Please sign in to comment.