Skip to content

Instantly share code, notes, and snippets.

@fmder
Created June 15, 2015 00:13
Show Gist options
  • Save fmder/d3bf5edf7cb535566835 to your computer and use it in GitHub Desktop.
Save fmder/d3bf5edf7cb535566835 to your computer and use it in GitHub Desktop.
Multi distance penality
class ClosestValidMultiPenality(object):
def __init__(self, feasibility, feasible, alpha, distance=None):
self.fbty_fct = feasibility
self.fbl_fct = feasible
self.alpha = alpha
self.dist_fct = distance
def __call__(self, func):
@wraps(func)
def wrapper(individual, *args, **kwargs):
if self.fbty_fct(individual):
return func(individual, *args, **kwargs)
f_ind = self.fbl_fct(individual)
# print("individual", f_ind)
f_fbl = func(f_ind, *args, **kwargs)
# print("feasible", f_fbl)
weights = tuple(1.0 if w >= 0 else -1.0 for w in individual.fitness.weights)
if len(weights) != len(f_fbl):
raise IndexError("Fitness weights and computed fitness are of different size.")
dist = 0
if self.dist_fct is not None:
dist = self.dist_fct(f_ind, individual)
# print("returned", tuple(f - w * self.alpha * dist for f, w in zip(f_fbl, weights)))
return tuple(f - w * self.alpha * d for f, w, d in zip(f_fbl, weights, dist))
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment