Пример #1
0
    def fitness(self, net, proc, id_for_printing=-1):
        total_weights = net.num_edges()
        total_delays = net.num_edges()
        total_thresholds = net.num_nodes()
        dec = [8] * total_weights + [4] * total_delays + [7] * total_thresholds
        leap_decoder = BinaryToIntDecoder(*dec)

        problem = NetworkProblem(net, proc, self)
        genome_len = 8 * total_weights + 4 * total_delays + 7 * total_thresholds
        parents = Individual.create_population(
            10,
            initialize=create_binary_sequence(genome_len),
            decoder=leap_decoder,
            problem=problem)
        parents = Individual.evaluate_population(parents)
        max_generation = 10
        #stdout_probe = probe.FitnessStatsCSVProbe(context, stream=sys.stdout)

        generation_counter = util.inc_generation(context=context)

        while generation_counter.generation() < max_generation:
            offspring = pipe(
                parents, ops.tournament_selection, ops.clone,
                mutate_bitflip, ops.uniform_crossover, ops.evaluate,
                ops.pool(size=len(parents)))  #,  # accumulate offspring
            #stdout_probe)

            parents = offspring
            generation_counter()  # increment to the next generation

        best = probe.best_of_gen(parents).decode()
        set_weights(best, net)
        return self.get_fitness_score(net, proc, id_for_printing)
Пример #2
0
"""
from toolz import pipe

from leap_ec.individual import Individual
from leap_ec.decoder import IdentityDecoder
from leap_ec.global_vars import context

import leap_ec.ops as ops
from leap_ec.binary_rep.problems import MaxOnes
from leap_ec.binary_rep.initializers import create_binary_sequence
from leap_ec.binary_rep.ops import mutate_bitflip
from leap_ec import util

# create initial rand population of 5 individuals
parents = Individual.create_population(5,
                                       initialize=create_binary_sequence(4),
                                       decoder=IdentityDecoder(),
                                       problem=MaxOnes())
# Evaluate initial population
parents = Individual.evaluate_population(parents)

# print initial, random population
util.print_population(parents, generation=0)

# generation_counter is an optional convenience for generation tracking
generation_counter = util.inc_generation(context=context)

while generation_counter.generation() < 6:
    offspring = pipe(parents, ops.tournament_selection, ops.clone,
                     mutate_bitflip(expected_num_mutations=1),
                     ops.uniform_crossover(p_swap=0.2), ops.evaluate,
Пример #3
0
from leap_ec.binary_rep.ops import mutate_bitflip

if __name__ == '__main__':
    pop_size = 5

    with open('./coop_stats.csv', 'w') as log_stream:
        ea = multi_population_ea(generations=1000, pop_size=pop_size,
                                 num_populations=9,
                                 problem=MaxOnes(),
                                 # Fitness function

                                 init_evaluate=ops.const_evaluate(value=-100),

                                 representation=Representation(
                                     individual_cls=Individual,
                                     initialize=create_binary_sequence(
                                         length=1),
                                     decoder=IdentityDecoder()
                                 ),

                                 # Operator pipeline
                                 shared_pipeline=[
                                     ops.tournament_selection,
                                     ops.clone,
                                     mutate_bitflip(expected_num_mutations=1),
                                     ops.CooperativeEvaluate(
                                         context=context,
                                         num_trials=1,
                                         collaborator_selector=ops.random_selection,
                                         log_stream=log_stream),
                                     ops.pool(size=pop_size)
                                 ])
Пример #4
0
        if args.track_workers_file:
            track_workers_stream = open(args.track_workers_file, 'w')
            track_workers_func = log_worker_location(track_workers_stream)

        if args.track_pop_file is not None:
            track_pop_stream = open(args.track_pop_file, 'w')
            track_pop_func = log_pop(args.update_interval, track_pop_stream)

        final_pop = asynchronous.steady_state(
            client,
            births=args.max_births,
            init_pop_size=args.init_pop_size,
            pop_size=args.pop_size,
            representation=Representation(
                initialize=create_binary_sequence(args.length),
                individual_cls=DistributedIndividual),
            problem=MaxOnes(),
            offspring_pipeline=[
                ops.random_selection, ops.clone,
                mutate_bitflip(expected_num_mutations=1),
                ops.pool(size=1)
            ],
            evaluated_probe=track_workers_func,
            pop_probe=track_pop_func)

        logger.info('Final pop: \n%s', pformat(final_pop))
    except Exception as e:
        logger.critical(str(e))
        raise e
    finally:
Пример #5
0
    # will take snapshots of the offspring before culling.  That way we can
    # compare the before and after to see what specific individuals were culled.
    offspring_probe = AttributesCSVProbe(attributes=['hostname',
                                           'pid',
                                           'uuid',
                                           'birth_id',
                                           'start_eval_time',
                                           'stop_eval_time'],
                               do_fitness=True,
                               stream=open('simple_sync_distributed_offspring.csv', 'w'))

    with Client() as client:
        # create an initial population of 5 parents of 4 bits each for the
        # MAX ONES problem
        parents = DistributedIndividual.create_population(5, # make five individuals
                                                          initialize=create_binary_sequence(
                                                              4), # with four bits
                                                          decoder=IdentityDecoder(),
                                                          problem=MaxOnes())

        # Scatter the initial parents to dask workers for evaluation
        parents = synchronous.eval_population(parents, client=client)

        # probes rely on this information for printing CSV 'step' column
        context['leap']['generation'] = 0

        probe(parents) # generation 0 is initial population
        offspring_probe(parents) # generation 0 is initial population

        # When running the test harness, just run for two generations
        # (we use this to quickly ensure our examples don't get bitrot)
        if os.environ.get(test_env_var, False) == 'True':
Пример #6
0
from leap_ec.binary_rep import initializers
from leap_ec.binary_rep import problems
from leap_ec.binary_rep.ops import mutate_bitflip

pop_size = 5
ea = generational_ea(
    generations=10,
    pop_size=pop_size,

    # Solve a MaxOnes Boolean optimization problem
    problem=problems.MaxOnes(),
    representation=representation.Representation(
        # Genotype and phenotype are the same for this task
        decoder=decoder.IdentityDecoder(),
        # Initial genomes are random binary sequences
        initialize=initializers.create_binary_sequence(length=10)),

    # The operator pipeline
    pipeline=[
        ops.tournament_selection,
        # Select parents via tournament_selection selection
        ops.clone,  # Copy them (just to be safe)
        # Basic mutation: defaults to a 1/L mutation rate
        mutate_bitflip,
        # Crossover with a 40% chance of swapping each gene
        ops.uniform_crossover(p_swap=0.4),
        ops.evaluate,  # Evaluate fitness
        # Collect offspring into a new population
        ops.pool(size=pop_size)
    ])