How to use the deap.tools function in deap

To help you get started, we’ve selected a few deap examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github HPC-buildtest / buildtest-framework / python / code / deap / basic_numpy.py View on Github external
def main():
    pop = toolbox.population(n=5)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)

    logbook = tools.Logbook()
    logbook.header = ["gen", "evals"] + stats.fields

    GEN = 1000
    best = None

    for g in range(GEN):
        for part in pop:
            part.fitness.values = toolbox.evaluate(part)
            if part.best is None or part.best.fitness < part.fitness:
                part.best = creator.Particle(part)
                part.best.fitness.values = part.fitness.values
            if best is None or best.fitness < part.fitness:
                best = creator.Particle(part)
                best.fitness.values = part.fitness.values
        for part in pop:
            toolbox.update(part, best)
github day0market / pyalgotrader / vnpy / app / cta_strategy / backtesting.py View on Github external
ga_strategy_class = self.strategy_class
        ga_setting = settings[0]
        ga_vt_symbol = self.vt_symbol
        ga_interval = self.interval
        ga_start = self.start
        ga_rate = self.rate
        ga_slippage = self.slippage
        ga_size = self.size
        ga_pricetick = self.pricetick
        ga_capital = self.capital
        ga_end = self.end
        ga_mode = self.mode

        # Set up genetic algorithem
        toolbox = base.Toolbox()
        toolbox.register("individual", tools.initIterate, creator.Individual, generate_parameter)
        toolbox.register("population", tools.initRepeat, list, toolbox.individual)
        toolbox.register("mate", tools.cxTwoPoint)
        toolbox.register("mutate", mutate_individual, indpb=1)
        toolbox.register("evaluate", ga_optimize)
        toolbox.register("select", tools.selNSGA2)

        total_size = len(settings)
        pop_size = population_size  # number of individuals in each generation
        lambda_ = pop_size  # number of children to produce at each generation
        mu = int(pop_size * 0.8)  # number of individuals to select for the next generation

        cxpb = 0.95  # probability that an offspring is produced by crossover
        mutpb = 1 - cxpb  # probability that an offspring is produced by mutation
        ngen = ngen_size  # number of generation

        pop = toolbox.population(pop_size)
github soravux / scoop / bench / evosn / multi_evosn.py View on Github external
open(args.filename).close()
    random.seed(64)
    
    beginTime = time.time()
    evaluationTime = 0

    population = toolbox.population(n=args.population)
    hof = tools.ParetoFront()
    
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", tools.mean)
    stats.register("std", tools.std)
    stats.register("min", min)
    stats.register("max", max)
    
    logger = tools.EvolutionLogger(["gen", "evals", "time"] + [str(k) for k in
        stats.functions.keys()])
    logger.logHeader()

    CXPB, MUTPB, ADDPB, DELPB, NGEN = 0.5, 0.2, 0.01, 0.01, args.generations
    
    evalBegin = time.time()
    # Evaluate every individuals
    fitnesses = toolbox.map(toolbox.evaluate, population)

    
    for ind, fit in zip(population, fitnesses):
        ind.fitness.values = fit

    evaluationTime += (time.time() - evalBegin)
    
    hof.update(population)
github chathika / NL4Py / Experiments / JSTATSOFTW2018 / Section3 / ParameterCalibrationWithDEAP.py View on Github external
# Open the model
n.openModel("models/Wolf Sheep Predation.nlogo")
# Get the parameter names and ranges.
parameterNames = n.getParamNames()
parameterRanges = n.getParamRanges()
parameterInitializers = []
# Iterate over the names and ranges and create DEAP initializers for all the parameters of the model
for parameterName, parameterRange in zip(parameterNames, parameterRanges):
    parameterName = ''.join(filter(str.isalnum, str(parameterName)))
    if len(parameterRange) == 3:
        print(str(parameterRange[0]) + " " + str(parameterRange[2]) + " " + str(parameterRange[1]))
        toolbox.register(parameterName, random.randrange, parameterRange[0], parameterRange[2], parameterRange[1]) #start stop step
        parameterInitializers.append(eval("toolbox."+str(parameterName)))
# Define the "individual" function in the DEAP toolbox which creates an Individual with a list of parameters
#  within the range specified by the NetLogo model interface.
toolbox.register("individual", tools.initCycle, creator.Individual, tuple(parameterInitializers))
# Define the "population" function in the DEAP toolbox
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# Define hyperparameters of the evolutionary algorithm
toolbox.register("mate", tools.cxTwoPoint)
lowerBounds = [row[1] for row in parameterRanges[:-2]]
upperBounds = [row[2] for row in parameterRanges[:-2]]
toolbox.register("mutate", tools.mutUniformInt, low = lowerBounds, up = upperBounds, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)

'''
Next, we define a simulation run. This involves:

1. Starting a NetLogoHeadlessWorkspace through NL4Py,
2. Opening the Wolf Sheep Predation model,
3. Setting the parameters to the values of the EA individual,
4. Running the simulation
github DEAP / deap / doc / code / tutorials / part_3 / logbook.py View on Github external
import pickle

from deap import tools

from stats import record

logbook = tools.Logbook()
logbook.record(gen=0, evals=30, **record)

print(logbook)

gen, avg = logbook.select("gen", "avg")

with open("logbook.pkl", "w") as lb_file:
	pickle.dump(logbook, lb_file)

# Cleaning the pickle file ...
import os
os.remove("logbook.pkl")

logbook.header = "gen", "avg", "spam"
print(logbook)
github pelillian / varro / varro / algo / strategies / sga.py View on Github external
# Load data from pickle file
            with open(self.ckpt, "rb") as cp_file:
                cp = pickle.load(cp_file)

            self.rndstate = random.seed(cp["rndstate"])
            self.pop = cp["pop"]
            self.curr_gen = int(cp["curr_gen"])
            self.halloffame = cp["halloffame"]
            self.logbook = cp["logbook"]

        else:
            # Start a new evolution
            self.rndstate = random.seed(100) # Set seed
            self.pop = self.toolbox.population(n=self.popsize)
            self.curr_gen = 0
            self.halloffame = tools.HallOfFame(maxsize=int(self.halloffamesize*self.popsize), similar=np.array_equal)
            self.logbook = tools.Logbook()

        self.paretofront = None
        logger.stop_timer('SGA.PY Loading ES Vars')
github pelillian / varro / varro / algo / strategies / es / toolbox.py View on Github external
logger.start_timer()

        # MUTATION
        toolbox.register("mutate",
                         getattr(tools, 'mutGaussian'),
                         mu=imutmu,
                         sigma=imutsigma,
                         indpb=imutpb)

        logger.stop_timer('TOOLBOX.PY register("mutate")')
        logger.start_timer()


        # POPULATION
        toolbox.register("population",
                         getattr(tools, 'initRepeat'),
                         list,
                         getattr(toolbox, 'individual'))

        logger.stop_timer('TOOLBOX.PY register("population")')
        logger.start_timer()

        # MATING
        toolbox.register("mate",
                         getattr(tools, 'cxTwoPoint'))

        logger.stop_timer('TOOLBOX.PY register("mate")')
        logger.start_timer()


    elif model_type == "fpga":
github Gab0 / japonicus / standard_generations.py View on Github external
def getToolbox(genconf):
    toolbox = base.Toolbox()
    creator.create("FitnessMax", base.Fitness, weights=(1.0,))
    creator.create("Individual", list,
                   fitness=creator.FitnessMax, Strategy=genconf.Strategy)
    toolbox.register("newind", initInd, creator.Individual)

    toolbox.register("population", tools.initRepeat, list,  toolbox.newind)

    toolbox.register("mate", tools.cxTwoPoint)
    toolbox.register("mutate", tools.mutUniformInt, low=10, up=10, indpb=0.2)

    return toolbox
github hhuhhu / vnpy_future / data_analysis / indicator_analysis / OptimizeIndicator.py View on Github external
def __init__(self, time_series, apply_price, process_num):
        self._time_series = time_series
        self._apply_price = time_series[apply_price].values
        self.signal, self.signal_bin = piecewise_linear(self._time_series[apply_price], 10, convert_trading_signals=False)
        self.pool = multiprocessing.Pool(process_num)
        self.toolbox = base.Toolbox()
        self.stats = tools.Statistics(lambda ind: ind.fitness.values)
github DEAP / deap / doc / code / tutorials / part_4 / 4_4_Using_Cpp_NSGA.py View on Github external
def main():
    random.seed(64)

    population = toolbox.population(n=300)
    hof = tools.ParetoFront()
    
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("Avg", tools.mean)
    stats.register("Std", tools.std)
    stats.register("Min", min)
    stats.register("Max", max)

    CXPB, MUTPB, ADDPB, DELPB, NGEN = 0.5, 0.2, 0.01, 0.01, 40
    
    # Evaluate every individuals
    fitnesses = toolbox.map(toolbox.evaluate, population)
    for ind, fit in zip(population, fitnesses):
        ind.fitness.values = fit
    
    hof.update(population)
    stats.update(population)
    
    # Begin the evolution
    for g in xrange(NGEN):
        print "-- Generation %i --" % g