Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom GA operators
def custom_crossover(genome, **kwargs):
mom = kwargs["mom"]
dad = kwargs["dad"]
mins = mom.getParam("min_constr")
maxes = mom.getParam("max_constr")
count = kwargs["count"]
sister = None
brother = None
if count >= 1:
sister = mom.clone()
sister.resetStats()
for i, pair in enumerate(izip(mom, dad)):
midpoint = (pair[0] + pair[1]) / 2
distance = abs(pair[0] - pair[1])
sister[i] = midpoint + distance * (random() - random())
if sister[i] < mins[i]:
sister[i] = mins[i]
elif sister[i] > maxes[i]:
sister[i] = maxes[i]
if count == 2:
brother = dad.clone()
brother.resetStats()
for i, pair in enumerate(izip(mom, dad)):
midpoint = (pair[0] + pair[1]) / 2
distance = abs(pair[0] - pair[1])
brother[i] = midpoint + distance * (random() - random())
if brother[i] < mins[i]:
brother[i] = mins[i]
elif brother[i] > maxes[i]:
brother[i] = maxes[i]
return (sister, brother)
def custom_initializer(genome, **kwargs):
# Minimal allowed values.
mins = genome.getParam("min_constr")
# Maximal allowed values.
maxes = genome.getParam("max_constr")
# Pseudo-allele initialization.
genome.genomeList = [uniform(mins[i], maxes[i])
for i in xrange(genome.getListSize())]
def custom_mutator(genome, **kwargs):
if kwargs["pmut"] <= 0.0:
return 0
size = len(genome) - 1
mutations = kwargs["pmut"] * (size + 1)
mins = genome.getParam("min_constr")
maxes = genome.getParam("max_constr")
if mutations < 1.0:
mutations = 0
for it in xrange(size + 1):
if Util.randomFlipCoin(kwargs["pmut"]):
genome[it] = uniform(mins[it], maxes[it])
mutations += 1
else:
assert False
for it in xrange(int(round(mutations))):
which_gene = randint(0, size)
genome[which_gene] = uniform(mins[which_gene], maxes[which_gene])
return int(mutations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.