Skip to content

Instantly share code, notes, and snippets.

@fmder
Last active December 28, 2015 16:29
Show Gist options
  • Save fmder/7529565 to your computer and use it in GitHub Desktop.
Save fmder/7529565 to your computer and use it in GitHub Desktop.
Initialization of individuals with other type of generators
import ghalton
import random
import json
from deap import base
from deap import creator
from deap import tools
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
IND_SIZE = 10
POP_SIZE = 30
# Shameless plug
# Nearly Orthogonal Latin Hypercube Samplings are taken from
# http://qrand.gel.ulaval.ca/
class NOLHRandom(object):
def __init__(self, dim):
"""Example of individual generator from a database of Nearly Orthogonal
Latin Hypercubes.
"""
# Load the sampling database
nolh = json.load(open("samplings.json"))
# Retreive the appropriate one
# JSON does not allow indexing by integer
sampling = nolh[str(dim)]
# There are a limited number of samples in Latin Hypercubes
if len(sampling) < POP_SIZE:
raise RuntimeError, "The NOLH contains only %d samples, you asked for %d" % (len(sampling), POP_SIZE)
self.iter = iter(sampling)
def next(self):
# Return the next sampling
return self.iter.next()
# ghalton is a module providing quasi random numbers.
# https://github.com/fmder/ghalton (another plug)
class QRandom(object):
def __init__(self, dim):
"""Example of unsing functions call to generate individuals.
"""
self.sequencer = ghalton.Halton(dim)
def next(self):
# The sequencer returns automatically the next point
# GHalton returns a list even when only one sample is required
return self.sequencer.get(1)[0]
# Choose the generator
generator = NOLHRandom(IND_SIZE)
# generator = QRandom(IND_SIZE)
toolbox = base.Toolbox()
# Use the tools.initIterate function since the next method returns a complete sequence
toolbox.register("individual", tools.initIterate, creator.Individual, generator.next)
toolbox.register("population", tools.initRepeat, list, toolbox.individual, n=POP_SIZE)
print toolbox.population()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment