Beispiel #1
0
    def run(self, plot_file=None):
        """
        GA repeatedly creates a village, runs it with values, then judges its
        performance and modifies values.
        Runs in groups of 10 villages.
        """
        gen = 0
        total_results = []
        P = self.init_P
        printing = False

        villages_per_gen = 30
        num_families = 10
        max_gens = 100
        max_fitness = 500
        use_ga = True
        elitism = True
        catastrophe = False
        presentation = True
        if use_ga:
            suptitle = 'Village evolution with GA'
        else:
            suptitle = 'Village evolution without GA'
        if catastrophe:
            suptitle += ' and with catastrophes'

        if presentation:
            fig = plt.figure(figsize=(8, 6), dpi=150,)
        else:
            fig = plt.figure(figsize=(12, 10), dpi=200,)
        ax = fig.add_subplot(111, aspect='auto')
        ax.set_xlabel('Generation')
        ax.set_ylabel('village trial')

        # FOR LIGHT PLOT
        #fig.suptitle(suptitle, fontsize=14, fontweight='bold')
        #cmap = 'GnBu'
        #facecolor = 'white'
        #fontcolor = 'black'

        # FOR DARK PLOT
        fig.set_facecolor('black')
        ax.set_axis_bgcolor('white')
        fig.suptitle(suptitle, fontsize=14, fontweight='bold', color='white')
        ax.spines['bottom'].set_color('gray')
        ax.spines['top'].set_color('gray')
        ax.spines['left'].set_color('gray')
        ax.spines['right'].set_color('gray')
        xa = ax.xaxis
        xa.set_tick_params(labelcolor='white')
        xa.label.set_color('white')
        ya = ax.yaxis
        ya.set_tick_params(labelcolor='white')
        ya.label.set_color('white')
        cmap='gist_earth'
        facecolor = 'black'
        fontcolor = 'white'
        if presentation:
            cmap = 'gist_ncar'

        fitness_array = np.zeros([villages_per_gen, max_gens])
        fit_plot = plt.imshow(fitness_array, interpolation='nearest',
                                cmap=cmap, origin='lower', vmin=0, vmax=max_fitness)
        ax.set_aspect('auto')
        cbar = plt.colorbar(fit_plot)
        cbytick_obj = plt.getp(cbar.ax.axes, 'yticklabels')
        plt.setp(cbytick_obj, color=fontcolor)

        # BEGIN EVOLUTION
        while gen < max_gens:
            results = []
            vill = None
            fitness = None
            print gen

            # RUN ONE VILLAGE FOR EACH GENOME
            P_index = 0
            for prof_designations in P:
                vill = Village(num_families, prof_designations)
                fitness = vill.run_village(max_fitness, printing,
                        catastrophe, presentation)
                #fitness, count_villagers, count_fams = 1, 2, 3
                results.append((fitness, prof_designations))
                vill = None

                # animation
                #curr_village = P.index(prof_designations)
                fitness_array[P_index][gen] = fitness
                #print 'f %s: %s' % (P_index, fitness)
                if presentation and P_index % 10 == 0:
                    fit_plot = plt.imshow(fitness_array, interpolation='nearest',
                                            cmap=cmap, origin='lower', vmin=0, vmax=400)
                    ax.set_aspect('auto')
                    plt.draw()
                    plt.show(block=False)
                P_index += 1

            # append set of 10 results to main set of results
            total_results.append(results)
            fit_plot = plt.imshow(fitness_array, interpolation='nearest',
                                    cmap=cmap, origin='lower', vmin=0, vmax=400)
            ax.set_aspect('auto')

            if elitism:
                fitnesses = [run[0] for run in results]
                indexes = range(len(P))
                max_fit_index = fitnesses.index(max(fitnesses))
                best_genome = P[max_fit_index][:]
            else:
                best_genome = None

            if use_ga:
                P = self.tournament_select(P, results, elitism, best_genome)
                #P = self.mutate(P, elitism, best_genome)
                #P = self.mutate_blocks(P, elitism, best_genome)
                P = self.mutate_elems(P, elitism, best_genome)
                P = self.alternate_crossover(P, elitism, best_genome)
                #P = self.three_point_crossover(P)

            else:
                # BASE: replace P with random vals
                P = []
                for x in range(villages_per_gen):
                    P.append(self.generate_genome())

            gen += 1

        plt.savefig(plot_file, bbox_inches=0, facecolor=facecolor)
        return total_results