Ejemplo n.º 1
0
def cgp_visual_probes(modulo):
    """Set up the graphical probes that we'll use."""
    plt.figure()
    p1 = probe.FitnessPlotProbe(modulo=modulo, ax=plt.gca())
    plt.figure()
    p2 = neural_network.GraphPhenotypeProbe(modulo=modulo, ax=plt.gca())
    return [p1, p2]
Ejemplo n.º 2
0
def build_probes(genomes_file, decoder):
    """Set up probes for writings results to file and terminal and
    displaying live metric plots."""
    assert (genomes_file is not None)

    probes = []

    # Print fitness stats to stdout
    probes.append(probe.FitnessStatsCSVProbe(stream=sys.stdout))

    # Save genome of the best individual to a file
    probes.append(
        probe.AttributesCSVProbe(stream=genomes_file,
                                 best_only=True,
                                 do_fitness=True,
                                 do_genome=True))

    # Open a figure to plot a fitness curve to
    plt.figure()
    plt.ylabel("Fitness")
    plt.xlabel("Generations")
    plt.title("Best-of-Generation Fitness")
    probes.append(
        probe.FitnessPlotProbe(ylim=(0, 1),
                               xlim=(0, 1),
                               modulo=1,
                               ax=plt.gca()))

    # Visualize the first two conditions of every rule
    plt.figure()
    plt.ylabel("Sensor 1")
    plt.xlabel("Sensor 0")
    plt.title("Rule Coverage")
    probes.append(
        rules.PlotPittRuleProbe(decoder,
                                xlim=(-1, 1),
                                ylim=(-1, 1),
                                ax=plt.gca()))

    return probes
Ejemplo n.º 3
0
def viz_plots(problems, modulo):
    """A convenience method that creates a figure with grid of subplots for
    visualizing the population genotypes and best-of-gen fitness for a number
    of different problems.

    :return: two lists of probe operators (for the phenotypes and fitness,
    respectively). Insert these into your algorithms to plot measurements to
    the respective subplots. """

    num_rows = min(4, len(problems))
    num_columns = math.ceil(len(problems) / num_rows)
    true_rows = len(problems) / num_columns
    fig = plt.figure(figsize=(6 * num_columns, 2.5 * true_rows))
    fig.tight_layout()
    genotype_probes = []
    fitness_probes = []
    for i, p in enumerate(problems):
        plt.subplot(true_rows, num_columns * 2, 2 * i + 1)
        tp = probe.CartesianPhenotypePlotProbe(contours=p,
                                               xlim=p.bounds,
                                               ylim=p.bounds,
                                               modulo=modulo,
                                               ax=plt.gca())
        genotype_probes.append(tp)

        plt.subplot(true_rows, num_columns * 2, 2 * i + 2)
        fp = probe.FitnessPlotProbe(ylim=(0, 1), modulo=modulo, ax=plt.gca())
        fitness_probes.append(fp)

    plt.subplots_adjust(left=0.05,
                        bottom=0.05,
                        right=0.95,
                        top=0.95,
                        wspace=0.2,
                        hspace=0.3)

    return genotype_probes, fitness_probes
Ejemplo n.º 4
0
def build_probes(genomes_file):
    """Set up probes for writings results to file and terminal and
    displaying live metric plots."""
    assert (genomes_file is not None)

    probes = []

    # Print fitness stats to stdout
    probes.append(probe.FitnessStatsCSVProbe(stream=sys.stdout))

    # Save genome of the best individual to a file
    probes.append(
        probe.AttributesCSVProbe(stream=genomes_file,
                                 best_only=True,
                                 do_fitness=True,
                                 do_genome=True))

    # Open a figure to plot a fitness curve to
    plt.figure()
    plt.ylabel("Fitness")
    plt.xlabel("Generations")
    plt.title("Best-of-Generation Fitness")
    probes.append(
        probe.FitnessPlotProbe(ylim=(0, 1),
                               xlim=(0, 1),
                               modulo=1,
                               ax=plt.gca()))

    # Open a figure to plot the best-of-gen network graph to
    plt.figure()
    probes.append(
        neural_network.GraphPhenotypeProbe(modulo=1,
                                           ax=plt.gca(),
                                           weights=True,
                                           weight_multiplier=3.0))

    return probes
Ejemplo n.º 5
0
                             ),

                             # Operator pipeline
                             pipeline=[
                                 ops.tournament_selection(k=2),
                                 ops.clone,
                                 # Apply binomial mutation: this is a lot like
                                 # additive Gaussian mutation, but adds an integer
                                 # value to each gene
                                 mutate_gaussian(std=0.2, hard_bounds=[problem.bounds]*l,
                                                 expected_num_mutations=1),
                                 ops.evaluate,
                                 ops.pool(size=pop_size),

                                 # Some visualization probes so we can watch what happens
                                 probe.CartesianPhenotypePlotProbe(
                                        xlim=problem.bounds,
                                        ylim=problem.bounds,
                                        contours=problem),
                                 probe.FitnessPlotProbe(),

                                 probe.PopulationMetricsPlotProbe(
                                     metrics=[ probe.pairwise_squared_distance_metric ],
                                     title='Population Diversity'),

                                 probe.FitnessStatsCSVProbe(stream=sys.stdout)
                             ]
                        )

    list(ea)
Ejemplo n.º 6
0
def ea_solve(function,
             bounds,
             generations=100,
             pop_size=cpu_count(),
             mutation_std=1.0,
             maximize=False,
             viz=False,
             viz_ylim=(0, 1),
             hard_bounds=True,
             dask_client=None):
    """Provides a simple, top-level interfact that optimizes a real-valued
    function using a simple generational EA.

    :param function: the function to optimize; should take lists of real
        numbers as input and return a float fitness value

    :param [(float, float)] bounds: a list of (min, max) bounds to define the
        search space

    :param int generations: the number of generations to run for
    :param int pop_size: the population size
    :param float mutation_std: the width of the mutation distribution
    :param bool maximize: whether to maximize the function (else minimize)
    :param bool viz: whether to display a live best-of-generation plot
    :param bool hard_bounds: if True, bounds are enforced at all times during
        evolution; otherwise they are only used to initialize the population.

    :param (float, float) viz_ylim: initial bounds to use of the plots
        vertical axis

    :param dask_client: is optional dask Client for enable parallel evaluations

    The basic call includes instrumentation that prints the best-so-far fitness
    value of each generation to stdout:

    >>> from leap_ec.simple import ea_solve
    >>> ea_solve(sum, bounds=[(0, 1)]*5) # doctest:+ELLIPSIS
    generation, bsf
    0, ...
    1, ...
    ...
    100, ...
    array([..., ..., ..., ..., ...])

    When `viz=True`, a live BSF plot will also display:

    >>> ea_solve(sum, bounds=[(0, 1)]*5, viz=True) # doctest:+ELLIPSIS
    generation, bsf
    0, ...
    1, ...
    ...
    100, ...
    array([..., ..., ..., ..., ...])

    .. plot::

        from leap_ec.simple import ea_solve
        ea_solve(sum, bounds=[(0, 1)]*5, viz=True)

    """

    if hard_bounds:
        mutation_op = mutate_gaussian(std=mutation_std,
                                      hard_bounds=bounds,
                                      expected_num_mutations='isotropic')
    else:
        mutation_op = mutate_gaussian(std=mutation_std,
                                      expected_num_mutations='isotropic')

    pipeline = [
        ops.tournament_selection,
        ops.clone,
        mutation_op,
        ops.uniform_crossover(p_swap=0.2),
    ]

    # If a dask client is given, then use the synchronous (map/reduce) parallel
    # evaluation of individuals; else, revert to serial evaluations.
    if dask_client:
        pipeline.append(
            synchronous.eval_pool(client=dask_client, size=pop_size))
    else:
        pipeline.extend([ops.evaluate, ops.pool(size=pop_size)])

    if viz:
        plot_probe = probe.FitnessPlotProbe(ylim=viz_ylim, ax=plt.gca())
        pipeline.append(plot_probe)

    ea = generational_ea(max_generations=generations,
                         pop_size=pop_size,
                         problem=FunctionProblem(function, maximize),
                         representation=Representation(
                             individual_cls=DistributedIndividual,
                             initialize=create_real_vector(bounds=bounds)),
                         pipeline=pipeline)

    best_genome = None
    print('generation, bsf')
    for g, ind in ea:
        print(f"{g}, {ind.fitness}")
        best_genome = ind.genome

    return best_genome
Ejemplo n.º 7
0
    # Uncomment these lines to see logs of what genomes and fitness values are sent to your external process.
    # This is useful for debugging a simulation.
    logging.getLogger().addHandler(logging.StreamHandler())  # Log to stderr
    logging.getLogger(leap_logger_name).setLevel(logging.DEBUG) # Log debug messages

    ##############################
    # Visualization probes
    ##############################
    # We set up visualizations in advance so that we can arrange them nicely
    plt.figure(figsize=(10, 5))
    plt.subplot(121)
    pop_probe = probe.CartesianPhenotypePlotProbe(xlim=problem.bounds, ylim=problem.bounds,
                                                  pad=[0.1, 0.1], ax=plt.gca(),
                                                  contours=problem, granularity=0.15)
    plt.subplot(122)
    fit_probe = probe.FitnessPlotProbe(ylim=[0, 0.1], ax=plt.gca())
    viz_probes = [pop_probe, fit_probe]

    ##############################
    # The Evolutionarly Algorithm
    ##############################
    ea = generational_ea(max_generations=generations, pop_size=pop_size,
                            problem=problem,  # Fitness function
                            
                            # By default, the initial population would be evaluated one-at-a-time.
                            # Passing group_evaluate into init_evaluate evaluates the population in batches.
                            init_evaluate=ops.grouped_evaluate(problem=problem, max_individuals_per_chunk=max_individuals_per_chunk),

                            # Representation
                            representation=Representation(
                                # Initialize a population of integer-vector genomes