Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Average from multiple simulations #2

Merged
merged 3 commits into from
Nov 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 57 additions & 55 deletions GeneticProgramming.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from deap import gp, creator, base, tools, algorithms
import networkx as nx
import matplotlib.pyplot as plt

from Simulation import run_simulation
import multiprocessing
from Simulation import fitness_function, run_simulation

def plot_logbook(logbook):
min_values = logbook.select("min")
Expand All @@ -27,15 +27,19 @@ def plot_tree(nodes, edges, labels):
nx.draw_networkx_labels(g, pos, labels)
plt.show()

def show_behaviour(best_individual):
best_individual_routine = gp.compile(best_individual, pset)
run_simulation(best_individual_routine, draw_grid=True)

def sequence3(input1, input2, input3):
for input in [input1, input2, input3]:
if input == False:
return False
elif input == True:
continue
else:
return input
return True
for input in [input1, input2, input3]:
if input == False:
return False
elif input == True:
continue
else:
return input
return True

def sequence2(input1, input2):
for input in [input1, input2]:
Expand All @@ -53,71 +57,69 @@ def selector2(input1, input2):
continue
else:
return input
return 'do_nothing'
return False

def selector3(input1, input2, input3):
for input in [input1, input2, input3]:
if input == False or input == True:
continue
else:
return input
return 'do_nothing'

return False

pset = gp.PrimitiveSet("main", 4)
pset.addPrimitive(sequence2, 2)
pset.addPrimitive(sequence3, 3)
pset.addPrimitive(selector2, 2)
pset.addPrimitive(selector3, 3)
pset.renameArguments(ARG0="food_nearby")
pset.renameArguments(ARG1="predator_nearby")
pset.renameArguments(ARG2="hunger_over_half")
pset.renameArguments(ARG3="over_reproduction_age")
pset.addTerminal('go_to_food')
pset.addTerminal('go_from_predator')
pset.addTerminal('do_nothing')
pset.addTerminal('eat')
pset.addTerminal('reproduce')

def eval_prey(individual):
routine = gp.compile(individual, pset)

res = fitness_function(routine)

return res,

creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("expr_init", gp.genFull, pset=pset, min_=1, max_=3)

toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr_init)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", eval_prey)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=1, max_=3)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)

if __name__ == '__main__':
pset = gp.PrimitiveSet("main", 4)

pset.addPrimitive(sequence2, 2)
pset.addPrimitive(sequence3, 3)
pset.addPrimitive(selector2, 2)
pset.addPrimitive(selector3, 3)

pset.renameArguments(ARG0="food_nearby")
pset.renameArguments(ARG1="predator_nearby")
pset.renameArguments(ARG2="hunger_over_half")
pset.renameArguments(ARG3="over_reproduction_age")
pset.addTerminal('go_to_food')
pset.addTerminal('go_from_predator')
pset.addTerminal('do_nothing')
pset.addTerminal('eat')
pset.addTerminal('reproduce')

creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMax)

toolbox = base.Toolbox()

toolbox.register("expr_init", gp.genFull, pset=pset, min_=1, max_=3)

toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr_init)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)


def eval_prey(individual):
routine = gp.compile(individual, pset)

res = run_simulation(routine)

return res,


toolbox.register("evaluate", eval_prey)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=1, max_=3)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)
cpu_count = multiprocessing.cpu_count()
pool = multiprocessing.Pool(cpu_count)
toolbox.register("map", pool.map)

pop = toolbox.population(n=10)
pop = toolbox.population(n=2)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.register("min", np.min)
stats.register("max", np.max)

_, logbook = algorithms.eaSimple(pop, toolbox, 0.5, 0.2, 50, stats, halloffame=hof)
_, logbook = algorithms.eaSimple(pop, toolbox, 0.5, 0.1, 2, stats, halloffame=hof)
plot_logbook(logbook)
nodes,edges,labels = gp.graph(hof[0])
plot_tree(nodes, edges, labels)
show_behaviour(hof[0])


6 changes: 5 additions & 1 deletion Simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
from GP_Agents import Prey, Predator
from matplotlib import pyplot as plt

def fitness_function(prey_function):
return np.mean([run_simulation(prey_function) for _ in range(3)])

def run_simulation(prey_function, print_move=False):
def run_simulation(prey_function, print_move=False, draw_grid=False):
parser = argparse.ArgumentParser()
parser.add_argument('--gridDim', default=50, type=int, help='Size of the grid')
parser.add_argument('--nPredators', default=100, type=int, help='Number of initial predators')
Expand Down Expand Up @@ -67,6 +69,7 @@ def run_simulation(prey_function, print_move=False):

for i in range(1, numLearningIterations):
numAgents = grid.update(True, i, ["prey"])
if draw_grid: grid.draw()
preyV.append(numAgents[0])
predV.append(numAgents[1])
grassV.append(numAgents[2])
Expand All @@ -81,6 +84,7 @@ def run_simulation(prey_function, print_move=False):

while numAgents[0] > 0 and i <= totalNumIterations:
numAgents = grid.update(False, i, ["prey"])
if draw_grid: grid.draw()
i += 1
preyV.append(numAgents[0])
predV.append(numAgents[1])
Expand Down