~ubuntu-branches/ubuntu/utopic/deap/utopic-proposed

« back to all changes in this revision

Viewing changes to examples/coev/coop_gen.py

  • Committer: Package Import Robot
  • Author(s): Daniel Stender, Miriam Ruiz, Daniel Stender, Jakub Wilk
  • Date: 2014-07-06 00:03:41 UTC
  • mfrom: (1.1.2)
  • Revision ID: package-import@ubuntu.com-20140706000341-s7gij1ki3d8xz6t9
Tags: 1.0.1-1
[ Miriam Ruiz ]
* New Upstream Release. Closes: #675200
* Upgraded Standards-Version from 3.9.2 to 3.9.5
* Switched to dh_python2
* Upgraded debian/compat to 9
* Added build-arch and build-indep targets to debian/rules
* Using awk to remove connection from the documentation to google analytics
* Using jquery.js and underscore.js from libjs-jquery and libjs-underscore
* Added patches/doc.patch

[ Daniel Stender ]
* deb/control:
  + Added myself to Uploaders.
  + Added version to b-p on python-all.
  + Updated Homepage.
  + Wrapped and sorted.
* deb/copyright:
  + Changed copyright file towards DEP-5.
  + Updated Source URI (project source moved to Github).
  + Added email addresses for copyright holders.
  + Dropped license for eap/toolbox.py (not included anymore).
  + Extended copyrights to 2014.
  + Added myself to copyrights for deb/*.
  + Specified license location.
* Added watch file [initial version by Jackson Doak].

[ Jakub Wilk ]
* Use canonical URIs for Vcs-* fields.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#    This file is part of DEAP.
 
2
#
 
3
#    DEAP is free software: you can redistribute it and/or modify
 
4
#    it under the terms of the GNU Lesser General Public License as
 
5
#    published by the Free Software Foundation, either version 3 of
 
6
#    the License, or (at your option) any later version.
 
7
#
 
8
#    DEAP is distributed in the hope that it will be useful,
 
9
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 
11
#    GNU Lesser General Public License for more details.
 
12
#
 
13
#    You should have received a copy of the GNU Lesser General Public
 
14
#    License along with DEAP. If not, see <http://www.gnu.org/licenses/>.
 
15
 
 
16
"""This example contains the generalizing test from *Potter, M. and De Jong,
 
17
K., 2001, Cooperative Coevolution: An Architecture for Evolving Co-adapted
 
18
Subcomponents.* section 4.2.2. Varying the *NUM_SPECIES* in :math:`[1, \ldots,
 
19
4]` will produce the results for one to four species respectively.
 
20
"""
 
21
 
 
22
import random
 
23
try:
 
24
    import matplotlib.pyplot as plt
 
25
except ImportError:
 
26
    plt = False
 
27
 
 
28
import numpy
 
29
 
 
30
from deap import algorithms
 
31
from deap import tools
 
32
 
 
33
import coop_base
 
34
 
 
35
IND_SIZE = coop_base.IND_SIZE
 
36
SPECIES_SIZE = coop_base.SPECIES_SIZE
 
37
NUM_SPECIES = 4
 
38
TARGET_SIZE = 30
 
39
 
 
40
noise =      "*##*###*###*****##*##****#*##*###*#****##******##*#**#*#**######"
 
41
schematas = ("1##1###1###11111##1##1111#1##1###1#1111##111111##1#11#1#11######",
 
42
             "1##1###1###11111##1##1000#0##0###0#0000##000000##0#00#0#00######",
 
43
             "0##0###0###00000##0##0000#0##0###0#0000##001111##1#11#1#11######")
 
44
 
 
45
toolbox = coop_base.toolbox
 
46
if plt:
 
47
    # This will allow to plot the match strength of every target schemata
 
48
    toolbox.register("evaluate_nonoise", coop_base.matchSetStrengthNoNoise)
 
49
 
 
50
def main(extended=True, verbose=True):
 
51
    target_set = []
 
52
    
 
53
    stats = tools.Statistics(lambda ind: ind.fitness.values)
 
54
    stats.register("avg", numpy.mean)
 
55
    stats.register("std", numpy.std)
 
56
    stats.register("min", numpy.min)
 
57
    stats.register("max", numpy.max)
 
58
    
 
59
    logbook = tools.Logbook()
 
60
    logbook.header = "gen", "species", "evals", "std", "min", "avg", "max"
 
61
    
 
62
    ngen = 150
 
63
    g = 0
 
64
    
 
65
    for i in range(len(schematas)):
 
66
        size = int(TARGET_SIZE/len(schematas))
 
67
        target_set.extend(toolbox.target_set(schematas[i], size))
 
68
    
 
69
    species = [toolbox.species() for _ in range(NUM_SPECIES)]
 
70
    
 
71
    # Init with random a representative for each species
 
72
    representatives = [random.choice(s) for s in species]
 
73
    
 
74
    if plt and extended:
 
75
        # We must save the match strength to plot them
 
76
        t1, t2, t3 = list(), list(), list()
 
77
    
 
78
    while g < ngen:
 
79
        # Initialize a container for the next generation representatives
 
80
        next_repr = [None] * len(species)
 
81
        for i, s in enumerate(species):
 
82
            # Vary the species individuals
 
83
            s = algorithms.varAnd(s, toolbox, 0.6, 1.0)
 
84
            
 
85
            # Get the representatives excluding the current species
 
86
            r = representatives[:i] + representatives[i+1:]
 
87
            for ind in s:
 
88
                ind.fitness.values = toolbox.evaluate([ind] + r, target_set)
 
89
                
 
90
            record = stats.compile(s)
 
91
            logbook.record(gen=g, species=i, evals=len(s), **record)
 
92
            
 
93
            if verbose: 
 
94
                print(logbook.stream)
 
95
            
 
96
            # Select the individuals
 
97
            species[i] = toolbox.select(s, len(s))  # Tournament selection
 
98
            next_repr[i] = toolbox.get_best(s)[0]   # Best selection
 
99
        
 
100
            g += 1
 
101
            
 
102
            if plt and extended:
 
103
                # Compute the match strength without noise for the
 
104
                # representatives on the three schematas
 
105
                t1.append(toolbox.evaluate_nonoise(representatives,
 
106
                    toolbox.target_set(schematas[0], 1), noise)[0])
 
107
                t2.append(toolbox.evaluate_nonoise(representatives,
 
108
                    toolbox.target_set(schematas[1], 1), noise)[0])
 
109
                t3.append(toolbox.evaluate_nonoise(representatives,
 
110
                    toolbox.target_set(schematas[2], 1), noise)[0])
 
111
            
 
112
        representatives = next_repr
 
113
    if extended:
 
114
        for r in representatives:
 
115
            # print individuals without noise
 
116
            print("".join(str(x) for x, y in zip(r, noise) if y == "*"))
 
117
    
 
118
    if plt and extended:
 
119
        # Do the final plotting
 
120
        plt.plot(t1, '-', color="k", label="Target 1")
 
121
        plt.plot(t2, '--', color="k", label="Target 2")
 
122
        plt.plot(t3, ':', color="k", label="Target 3")
 
123
        plt.legend(loc="lower right")
 
124
        plt.axis([0, ngen, 0, max(max(t1), max(t2), max(t3)) + 1])
 
125
        plt.xlabel("Generations")
 
126
        plt.ylabel("Number of matched bits")
 
127
        plt.show()
 
128
    
 
129
if __name__ == "__main__":
 
130
    main()