Skip to content

Commit

Permalink
Trying to fix usage test
Browse files Browse the repository at this point in the history
  • Loading branch information
Julian Blank committed Nov 19, 2020
1 parent 11e745f commit 75ad2b2
Show file tree
Hide file tree
Showing 14 changed files with 449 additions and 71 deletions.
88 changes: 88 additions & 0 deletions pymoo/algorithms/addon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import json
from urllib.request import urlopen

import numpy as np
import requests

from pymoo.algorithms.nsga2 import NSGA2
from pymoo.factory import get_problem
from pymoo.model.infill import InfillCriterion
from pymoo.model.population import Population
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter


def numpy_to_json(x):
s = len(x.shape)
if s == 1:
return x.tolist()
elif s == 2:
return [e.tolist() for e in x]


def get_url():
return urlopen("http://pymoo.org/addon.txt").read().decode('utf-8').replace("\n", "")


# =========================================================================================================
# Remote Calls
# =========================================================================================================


class RemoteInfillCriterion(InfillCriterion):

def __init__(self, endpoint, params={}, **kwargs):
super().__init__(**kwargs)
self.endpoint = endpoint
self.url = get_url()
self.params = params

def do(self, problem, pop, n_offsprings, **kwargs):
X, F, G = pop.get("X", "F", "G")
xl, xu = problem.bounds()

# defining a params dict for the parameters to be sent to the API
DATA = {'X': numpy_to_json(X),
'F': numpy_to_json(F),
'xl': numpy_to_json(xl),
'xu': numpy_to_json(xu),
}

if problem.has_constraints():
DATA['G'] = numpy_to_json(G)

DATA = {**DATA,
'n_infills': n_offsprings,
**self.params}

# sending get request and saving the response as response object
r = requests.post(url=f"{self.url}/{self.endpoint}", json=json.dumps(DATA))

# extracting data in json format
resp = r.json()

if not resp["success"]:
raise Exception(f"ERROR during remote call: {resp['error']}")

X = np.array(resp["X"])

return Population.new(X=X)


class SANSGA2(NSGA2):

def __init__(self, **kwargs):
super().__init__(mating=RemoteInfillCriterion("sansga2"), **kwargs)


problem = get_problem("zdt1", n_var=10)

algorithm = SANSGA2(n_offsprings=10)

res = minimize(problem,
algorithm,
('n_gen', 20),
seed=1,
verbose=True)

Scatter().add(res.F).show()
4 changes: 2 additions & 2 deletions pymoo/algorithms/ctaea.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,14 +142,14 @@ def _initialize(self):
self.pop = pop
self.da = da

def _solve(self, problem):
def setup(self, problem, **kwargs):

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

return super()._solve(problem)
return super().setup(problem)

def _next(self):

Expand Down
3 changes: 2 additions & 1 deletion pymoo/algorithms/gde3.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ def __init__(self, **kwargs):
def _next(self):

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

# evaluate the offsprings
self.evaluator.eval(self.problem, self.off, algorithm=self)
Expand Down
36 changes: 13 additions & 23 deletions pymoo/algorithms/mocs.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,27 @@
import math
import numpy as np
from itertools import combinations

from pymoo.algorithms.nsga2 import RankAndCrowdingSurvival
from pymoo.algorithms.so_cuckoo_search import CuckooSearch
from pymoo.docs import parse_doc_string
from pymoo.model.algorithm import Algorithm
from pymoo.model.duplicate import DefaultDuplicateElimination
from pymoo.model.initialization import Initialization
from pymoo.model.population import Population
from pymoo.model.replacement import ImprovementReplacement, is_better
from pymoo.operators.repair.to_bound import set_to_bounds_if_outside_by_problem
from pymoo.operators.sampling.random_sampling import FloatRandomSampling
from pymoo.util.display import MultiObjectiveDisplay
from pymoo.util.misc import has_feasible

class MOCSDisplay(MultiObjectiveDisplay):
def _do(self, problem, evaluator, algorithm):
super()._do(problem, evaluator, algorithm)

class MOCS(CuckooSearch):

def __init__(self,
display=MOCSDisplay(),
sampling=FloatRandomSampling(),
survival=RankAndCrowdingSurvival(),
eliminate_duplicates=DefaultDuplicateElimination(),
termination=None,
pop_size=100,
beta=1.5,
alfa=0.1,
alpha=0.1,
pa=0.35,
display=MultiObjectiveDisplay(),
sampling=FloatRandomSampling(),
survival=RankAndCrowdingSurvival(),
eliminate_duplicates=DefaultDuplicateElimination(),
**kwargs):
"""
Expand All @@ -47,7 +38,7 @@ def __init__(self,
beta : The input parameter of the Mantegna's Algorithm to simulate
sampling on Levy Distribution
alfa : The scaling step size and is usually O(L/100) with L is the
alpha : The scaling step size and is usually O(L/100) with L is the
scale of the problem
pa : The switch probability, pa fraction of the nests will be
Expand All @@ -58,10 +49,9 @@ def __init__(self,
sampling=sampling,
survival=survival,
eliminate_duplicates=eliminate_duplicates,
termination=termination,
pop_size=pop_size,
beta=beta,
alfa=alfa,
alpha=alpha,
pa=pa,
**kwargs)

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

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

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

#Evaluate
# Evaluate
off = Population(len(_X)).set("X", _X)
self.evaluator.eval(self.problem, off, algorithm=self)

#Local Random Walk
# Local Random Walk
_X = off.get("X")
dir_vec = self._get_local_directional_vector(X)
_X = _X + dir_vec
_X = set_to_bounds_if_outside_by_problem(self.problem, _X)
off = Population(len(_X)).set("X", _X)
self.evaluator.eval(self.problem, off, algorithm=self)

#append offspring to population and then sort for elitism (survival)
# append offspring to population and then sort for elitism (survival)
self.pop = Population.merge(pop, off)
self.pop = self.survival.do(self.problem, self.pop, self.pop_size, algorithm=self)

Expand Down
4 changes: 2 additions & 2 deletions pymoo/algorithms/rnsga3.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ def __init__(self,
n_offsprings=n_offsprings,
**kwargs)

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

return super()._solve(problem)
return super().setup(problem, **kwargs)

def _finalize(self):
pass
Expand Down
Loading

0 comments on commit 75ad2b2

Please sign in to comment.