Skip to content

Commit 1504986

Browse files
author
Julian Blank
committed
Trying to fix usage test
1 parent cca316e commit 1504986

File tree

14 files changed

+449
-71
lines changed

14 files changed

+449
-71
lines changed

pymoo/algorithms/addon.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import json
2+
from urllib.request import urlopen
3+
4+
import numpy as np
5+
import requests
6+
7+
from pymoo.algorithms.nsga2 import NSGA2
8+
from pymoo.factory import get_problem
9+
from pymoo.model.infill import InfillCriterion
10+
from pymoo.model.population import Population
11+
from pymoo.optimize import minimize
12+
from pymoo.visualization.scatter import Scatter
13+
14+
15+
def numpy_to_json(x):
16+
s = len(x.shape)
17+
if s == 1:
18+
return x.tolist()
19+
elif s == 2:
20+
return [e.tolist() for e in x]
21+
22+
23+
def get_url():
24+
return urlopen("http://pymoo.org/addon.txt").read().decode('utf-8').replace("\n", "")
25+
26+
27+
# =========================================================================================================
28+
# Remote Calls
29+
# =========================================================================================================
30+
31+
32+
class RemoteInfillCriterion(InfillCriterion):
33+
34+
def __init__(self, endpoint, params={}, **kwargs):
35+
super().__init__(**kwargs)
36+
self.endpoint = endpoint
37+
self.url = get_url()
38+
self.params = params
39+
40+
def do(self, problem, pop, n_offsprings, **kwargs):
41+
X, F, G = pop.get("X", "F", "G")
42+
xl, xu = problem.bounds()
43+
44+
# defining a params dict for the parameters to be sent to the API
45+
DATA = {'X': numpy_to_json(X),
46+
'F': numpy_to_json(F),
47+
'xl': numpy_to_json(xl),
48+
'xu': numpy_to_json(xu),
49+
}
50+
51+
if problem.has_constraints():
52+
DATA['G'] = numpy_to_json(G)
53+
54+
DATA = {**DATA,
55+
'n_infills': n_offsprings,
56+
**self.params}
57+
58+
# sending get request and saving the response as response object
59+
r = requests.post(url=f"{self.url}/{self.endpoint}", json=json.dumps(DATA))
60+
61+
# extracting data in json format
62+
resp = r.json()
63+
64+
if not resp["success"]:
65+
raise Exception(f"ERROR during remote call: {resp['error']}")
66+
67+
X = np.array(resp["X"])
68+
69+
return Population.new(X=X)
70+
71+
72+
class SANSGA2(NSGA2):
73+
74+
def __init__(self, **kwargs):
75+
super().__init__(mating=RemoteInfillCriterion("sansga2"), **kwargs)
76+
77+
78+
problem = get_problem("zdt1", n_var=10)
79+
80+
algorithm = SANSGA2(n_offsprings=10)
81+
82+
res = minimize(problem,
83+
algorithm,
84+
('n_gen', 20),
85+
seed=1,
86+
verbose=True)
87+
88+
Scatter().add(res.F).show()

pymoo/algorithms/ctaea.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,14 +142,14 @@ def _initialize(self):
142142
self.pop = pop
143143
self.da = da
144144

145-
def _solve(self, problem):
145+
def setup(self, problem, **kwargs):
146146

147147
if self.ref_dirs is not None and self.ref_dirs.shape[1] != problem.n_obj:
148148
raise Exception(
149149
"Dimensionality of reference points must be equal to the number of objectives: %s != %s" %
150150
(self.ref_dirs.shape[1], problem.n_obj))
151151

152-
return super()._solve(problem)
152+
return super().setup(problem)
153153

154154
def _next(self):
155155

pymoo/algorithms/gde3.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ def __init__(self, **kwargs):
1414
def _next(self):
1515

1616
# make a step and create the offsprings
17-
self.off = self._step()
17+
self.off = self.mating.do(self.problem, self.pop, self.n_offsprings, algorithm=self)
18+
self.off.set("n_gen", self.n_gen)
1819

1920
# evaluate the offsprings
2021
self.evaluator.eval(self.problem, self.off, algorithm=self)

pymoo/algorithms/mocs.py

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,27 @@
1-
import math
21
import numpy as np
3-
from itertools import combinations
42

53
from pymoo.algorithms.nsga2 import RankAndCrowdingSurvival
64
from pymoo.algorithms.so_cuckoo_search import CuckooSearch
75
from pymoo.docs import parse_doc_string
8-
from pymoo.model.algorithm import Algorithm
96
from pymoo.model.duplicate import DefaultDuplicateElimination
10-
from pymoo.model.initialization import Initialization
117
from pymoo.model.population import Population
12-
from pymoo.model.replacement import ImprovementReplacement, is_better
138
from pymoo.operators.repair.to_bound import set_to_bounds_if_outside_by_problem
149
from pymoo.operators.sampling.random_sampling import FloatRandomSampling
1510
from pymoo.util.display import MultiObjectiveDisplay
1611
from pymoo.util.misc import has_feasible
1712

18-
class MOCSDisplay(MultiObjectiveDisplay):
19-
def _do(self, problem, evaluator, algorithm):
20-
super()._do(problem, evaluator, algorithm)
2113

2214
class MOCS(CuckooSearch):
2315

2416
def __init__(self,
25-
display=MOCSDisplay(),
26-
sampling=FloatRandomSampling(),
27-
survival=RankAndCrowdingSurvival(),
28-
eliminate_duplicates=DefaultDuplicateElimination(),
29-
termination=None,
3017
pop_size=100,
3118
beta=1.5,
32-
alfa=0.1,
19+
alpha=0.1,
3320
pa=0.35,
21+
display=MultiObjectiveDisplay(),
22+
sampling=FloatRandomSampling(),
23+
survival=RankAndCrowdingSurvival(),
24+
eliminate_duplicates=DefaultDuplicateElimination(),
3425
**kwargs):
3526
"""
3627
@@ -47,7 +38,7 @@ def __init__(self,
4738
beta : The input parameter of the Mantegna's Algorithm to simulate
4839
sampling on Levy Distribution
4940
50-
alfa : The scaling step size and is usually O(L/100) with L is the
41+
alpha : The scaling step size and is usually O(L/100) with L is the
5142
scale of the problem
5243
5344
pa : The switch probability, pa fraction of the nests will be
@@ -58,10 +49,9 @@ def __init__(self,
5849
sampling=sampling,
5950
survival=survival,
6051
eliminate_duplicates=eliminate_duplicates,
61-
termination=termination,
6252
pop_size=pop_size,
6353
beta=beta,
64-
alfa=alfa,
54+
alpha=alpha,
6555
pa=pa,
6656
**kwargs)
6757

@@ -76,28 +66,28 @@ def _step(self):
7666
X = pop.get("X")
7767
F = pop.get("F")
7868

79-
#Levy Flight
80-
#pick the best one from random optimum nests (leas infeasibles or PF members)
69+
# Levy Flight
70+
# pick the best one from random optimum nests (leas infeasibles or PF members)
8171
best = self.opt[np.random.randint(len(self.opt), size=len(X))]
8272
G_X = np.array([best_nest.get("X") for best_nest in best])
8373

8474
step_size = self._get_global_step_size(X)
85-
_X = X + np.random.rand(*X.shape)*step_size*(G_X-X)
75+
_X = X + np.random.rand(*X.shape) * step_size * (G_X - X)
8676
_X = set_to_bounds_if_outside_by_problem(self.problem, _X)
8777

88-
#Evaluate
78+
# Evaluate
8979
off = Population(len(_X)).set("X", _X)
9080
self.evaluator.eval(self.problem, off, algorithm=self)
9181

92-
#Local Random Walk
82+
# Local Random Walk
9383
_X = off.get("X")
9484
dir_vec = self._get_local_directional_vector(X)
9585
_X = _X + dir_vec
9686
_X = set_to_bounds_if_outside_by_problem(self.problem, _X)
9787
off = Population(len(_X)).set("X", _X)
9888
self.evaluator.eval(self.problem, off, algorithm=self)
9989

100-
#append offspring to population and then sort for elitism (survival)
90+
# append offspring to population and then sort for elitism (survival)
10191
self.pop = Population.merge(pop, off)
10292
self.pop = self.survival.do(self.problem, self.pop, self.pop_size, algorithm=self)
10393

pymoo/algorithms/rnsga3.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,12 @@ def __init__(self,
7878
n_offsprings=n_offsprings,
7979
**kwargs)
8080

81-
def _solve(self, problem):
81+
def setup(self, problem, **kwargs):
8282
if self.survival.ref_points.shape[1] != problem.n_obj:
8383
raise Exception("Dimensionality of reference points must be equal to the number of objectives: %s != %s" %
8484
(self.survival.ref_points.shape[1], problem.n_obj))
8585

86-
return super()._solve(problem)
86+
return super().setup(problem, **kwargs)
8787

8888
def _finalize(self):
8989
pass

0 commit comments

Comments
 (0)