1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
|
# This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with DEAP. If not, see <http://www.gnu.org/licenses/>.
"""
This example is from "John R. Koza. Genetic Programming: On the Programming
of Computers by Natural Selection. MIT Press, Cambridge, MA, USA, 1992.".
The problem is called The Artificial Ant Problem.
<http://www.cs.ucl.ac.uk/staff/w.langdon/bloat_csrp-97-29/node2.html>
The goal of this example is to show how to use DEAP and its GP framework with
with complex system of functions and object.
Given an AntSimulator ant, this solution should get the 89 pieces of food
within 543 moves.
ant.routine = ant.if_food_ahead(ant.move_forward, prog3(ant.turn_left,
prog2(ant.if_food_ahead(ant.move_forward, ant.turn_right),
prog2(ant.turn_right, prog2(ant.turn_left, ant.turn_right))),
prog2(ant.if_food_ahead(ant.move_forward, ant.turn_left), ant.move_forward)))
Best solution found with DEAP:
prog3(prog3(move_forward,
turn_right,
if_food_ahead(if_food_ahead(prog3(move_forward,
move_forward,
move_forward),
prog2(turn_left,
turn_right)),
turn_left)),
if_food_ahead(turn_left,
turn_left),
if_food_ahead(move_forward,
turn_right))
fitness = (89,)
"""
import copy
import random
import numpy
from functools import partial
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from deap import gp
def progn(*args):
for arg in args:
arg()
def prog2(out1, out2):
return partial(progn,out1,out2)
def prog3(out1, out2, out3):
return partial(progn,out1,out2,out3)
def if_then_else(condition, out1, out2):
out1() if condition() else out2()
class AntSimulator(object):
direction = ["north","east","south","west"]
dir_row = [1, 0, -1, 0]
dir_col = [0, 1, 0, -1]
def __init__(self, max_moves):
self.max_moves = max_moves
self.moves = 0
self.eaten = 0
self.routine = None
def _reset(self):
self.row = self.row_start
self.col = self.col_start
self.dir = 1
self.moves = 0
self.eaten = 0
self.matrix_exc = copy.deepcopy(self.matrix)
@property
def position(self):
return (self.row, self.col, self.direction[self.dir])
def turn_left(self):
if self.moves < self.max_moves:
self.moves += 1
self.dir = (self.dir - 1) % 4
def turn_right(self):
if self.moves < self.max_moves:
self.moves += 1
self.dir = (self.dir + 1) % 4
def move_forward(self):
if self.moves < self.max_moves:
self.moves += 1
self.row = (self.row + self.dir_row[self.dir]) % self.matrix_row
self.col = (self.col + self.dir_col[self.dir]) % self.matrix_col
if self.matrix_exc[self.row][self.col] == "food":
self.eaten += 1
self.matrix_exc[self.row][self.col] = "passed"
def sense_food(self):
ahead_row = (self.row + self.dir_row[self.dir]) % self.matrix_row
ahead_col = (self.col + self.dir_col[self.dir]) % self.matrix_col
return self.matrix_exc[ahead_row][ahead_col] == "food"
def if_food_ahead(self, out1, out2):
return partial(if_then_else, self.sense_food, out1, out2)
def run(self,routine):
self._reset()
while self.moves < self.max_moves:
routine()
def parse_matrix(self, matrix):
self.matrix = list()
for i, line in enumerate(matrix):
self.matrix.append(list())
for j, col in enumerate(line):
if col == "#":
self.matrix[-1].append("food")
elif col == ".":
self.matrix[-1].append("empty")
elif col == "S":
self.matrix[-1].append("empty")
self.row_start = self.row = i
self.col_start = self.col = j
self.dir = 1
self.matrix_row = len(self.matrix)
self.matrix_col = len(self.matrix[0])
self.matrix_exc = copy.deepcopy(self.matrix)
ant = AntSimulator(600)
pset = gp.PrimitiveSet("MAIN", 0)
pset.addPrimitive(ant.if_food_ahead, 2)
pset.addPrimitive(prog2, 2)
pset.addPrimitive(prog3, 3)
pset.addTerminal(ant.move_forward)
pset.addTerminal(ant.turn_left)
pset.addTerminal(ant.turn_right)
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
# Attribute generator
toolbox.register("expr_init", gp.genFull, pset=pset, min_=1, max_=2)
# Structure initializers
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr_init)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
def evalArtificialAnt(individual):
# Transform the tree expression to functional Python code
routine = gp.compile(individual, pset)
# Run the generated routine
ant.run(routine)
return ant.eaten,
toolbox.register("evaluate", evalArtificialAnt)
toolbox.register("select", tools.selTournament, tournsize=7)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)
def main():
random.seed(69)
with open("ant/santafe_trail.txt") as trail_file:
ant.parse_matrix(trail_file)
pop = toolbox.population(n=300)
hof = tools.HallOfFame(1)
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)
algorithms.eaSimple(pop, toolbox, 0.5, 0.2, 40, stats, halloffame=hof)
return pop, hof, stats
if __name__ == "__main__":
main()
|