-
Notifications
You must be signed in to change notification settings - Fork 0
/
hyperneatEvolveAuto.py
242 lines (203 loc) · 7.77 KB
/
hyperneatEvolveAuto.py
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
Using hyperneat to evolve .
"""
from __future__ import print_function
import os
import neat
import neat.nn
import visualize
import numpy as np
try:
import cPickle as pickle
except:
import pickle
from DeliveryMapAuto import MultiAgentDeliveryEnv
from pureples.shared.substrate import Substrate
from pureples.shared.visualize import draw_net
from pureples.es_hyperneat.es_hyperneat import ESNetwork
import random
import heapq
SIZE = 20
input_coordinates = []
for i in range(SIZE):
x = i * 1.9/(SIZE - 1) - 0.95
for j in range(SIZE):
y = j * 1.9/(SIZE - 1) - 0.95
input_coordinates.append((x, y))
input_coordinates.append((0.0, -1.0)) #distance
input_coordinates.append((1.0, 1.0)) #bias
#include a bias
output_coordinates = [(0.0, 1.0)] #must me this coor or it bugs out
sub = Substrate(input_coordinates, output_coordinates)
params = {"initial_depth": 2,
"max_depth": 4,
"variance_threshold": 0.4,
"band_threshold": 0.3,
"iteration_level": 1,
"division_threshold": 0.5,
"max_weight": 15.0,
"activation": "sigmoid"}
def convert(list):
return tuple(float(i)/2 for i in list)
# def train(net, network, render, env = MultiAgentDeliveryEnv()):
# episode_reward = 0
# step = 1
# current_state = env.reset()
# done = False
# net.reset()
# while not done and step < 999:
# numAction = []
# for action in current_state:
# action = np.append(action, [1]) #bias
# action = convert(action)
# for k in range(network.activations):
# o = net.activate(action)
# numAction.append(o)
# action = np.argmax(numAction)
# new_state, reward, done = env.step(action)
# if render:
# env.render(500)
# print(action)
# episode_reward += reward
# current_state = new_state
# step += 1
# if render:
# print(episode_reward)
# # Append episode reward to a list and log stats (every given number of episodes)
# return episode_reward
def trainMultiple(genomes, config, render, env):
step = 0
current_state = env.reset()
done = False
nets = []
networks = []
rewards = np.zeros(len(genomes))
for genome_id, genome in genomes:
cppn = neat.nn.FeedForwardNetwork.create(genome, config)
network = ESNetwork(sub, cppn, params)
net = network.create_phenotype_network()
nets.append(net)
networks.append(network)
pq = []
for i in range(len(nets)):
heapq.heappush(pq, (0, i))
while not done and step < 1000:
time, index = heapq.heappop(pq)
network = networks[index]
net = nets[index]
numAction = []
for action in current_state:
action = np.append(action, [1]) #bias
action = convert(action)
for k in range(network.activations):
o = net.activate(action)
numAction.append(o)
action = np.argmax(numAction)
new_state, reward, done, distance = env.stepM(action, index)
if render:
env.render(100)
print(action)
rewards[index] += reward
heapq.heappush(pq, (time + distance, index))
current_state = new_state
step += 1
if render:
print(rewards)
# Append episode reward to a list and log stats (every given number of episodes)
return rewards
# def eval_genome(genome, config):
# cppn = neat.nn.FeedForwardNetwork.create(genome, config)
# network = ESNetwork(sub, cppn, params)
# net = network.create_phenotype_network()
# episode_reward = 0
# runs = 10
# for i in range(runs):
# episode_reward += train(net, network, False)
# fitness = episode_reward/runs
# # Append episode reward to a list and log stats (every given number of episodes)
# return fitness
# def eval_genomes(genomes, config):
# best_net = (None, None, -9999)
# runs = 10
# environments = [MultiAgentDeliveryEnv() for i in range(runs)]
# for genome_id, genome in genomes:
# cppn = neat.nn.FeedForwardNetwork.create(genome, config)
# network = ESNetwork(sub, cppn, params)
# net = network.create_phenotype_network()
# episode_reward = 0
# genome.fitness = 0
# for i in range(runs):
# episode_reward += train(net, network, False, environments[i])
# fitness = episode_reward/runs
# if fitness > best_net[2]:
# best_net = (net, network, fitness)
# # Append episode reward to a list and log stats (every given number of episodes)
# genome.fitness += fitness
# for i in range(4):
# train(best_net[0], best_net[1], True)
def eval_multipleGenomes(genomes, config):
runs = 10
environments = [MultiAgentDeliveryEnv(len(genomes)) for i in range(runs)]
rewards = np.zeros(len(genomes))
for i in range(runs):
rewards += trainMultiple(genomes, config, False, environments[i])
rewards = rewards/runs
i = 0
for genome_id, genome in genomes:
fitness = rewards[i]
genome.fitness = 0
genome.fitness += fitness
i+=1
trainMultiple(genomes, config, True, environments[0])
def run(config_file):
# Load configuration.
config = neat.config.Config(neat.genome.DefaultGenome, neat.reproduction.DefaultReproduction,
neat.species.DefaultSpeciesSet, neat.stagnation.DefaultStagnation,
config_file)
# Create the population, which is the top-level object for a NEAT run.
#p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-15')
# Add a stdout reporter to show progress in the terminal.
pop = neat.population.Population(config)
stats = neat.statistics.StatisticsReporter()
pop.add_reporter(stats)
pop.add_reporter(neat.reporting.StdOutReporter(True))
pop.add_reporter(neat.Checkpointer(999))
#p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-299')
# Run for up to 300 generations.
winner = pop.run(eval_multipleGenomes, 300)
# Display the winning genome.
print('\nBest genome:\n{!s}'.format(winner))
# Show output of the most fit genome against training data.
print('\nOutput:')
cppn = neat.nn.FeedForwardNetwork.create(winner, config)
network = ESNetwork(sub, cppn, params)
winner_net = network.create_phenotype_network(filename='es_hyperneat_winner.png')
input("Winner is found")
for i in range(10):
train(winner_net, network, True)
draw_net(cppn, filename="es_hyperneat")
#visualize.draw_net(config, winner, True, node_names=node_names)
#visualize.plot_stats(stats, ylog=False, view=True)
#visualize.plot_species(stats, view=True)
if __name__ == '__main__':
# Determine path to configuration file. This path manipulation is
# here so that the script will run successfully regardless of the
# current working directory.
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'Config')
run(config_path)
# config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
# neat.DefaultSpeciesSet, neat.DefaultStagnation,
# config_path)
# p = neat.Population(config)
# p.add_reporter(neat.StdOutReporter(True))
# stats = neat.StatisticsReporter()
# p.add_reporter(stats)
# p.add_reporter(neat.Checkpointer(5))
# p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-24')
# winner = p.run(eval_genomes, 1)
# cppn = neat.nn.RecurrentNetwork.create(winner, config)
# network = ESNetwork(sub, cppn, params)
# winner_net = network.create_phenotype_network(filename='es_hyperneat_winner.png')
# for i in range(10):
# train(winner_net, True)