-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualize.py
257 lines (196 loc) · 7.92 KB
/
visualize.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
from __future__ import print_function
import copy
import warnings
import graphviz
import matplotlib.pyplot as plt
import numpy as np
import os
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
""" Plots the population's average and best fitness. """
if plt is None:
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
return
generation = range(len(statistics.most_fit_genomes))
best_fitness = [c.fitness for c in statistics.most_fit_genomes]
avg_fitness = np.array(statistics.get_fitness_mean())
stdev_fitness = np.array(statistics.get_fitness_stdev())
plt.plot(generation, avg_fitness, 'b-', label="average")
plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
plt.plot(generation, best_fitness, 'r-', label="best")
plt.title("Population's average and best fitness")
plt.xlabel("Generations")
plt.ylabel("Fitness")
plt.grid()
plt.legend(loc="best")
if ylog:
plt.gca().set_yscale('symlog')
plt.savefig(filename)
if view:
plt.show()
plt.close()
def plot_spikes(spikes, view=False, filename=None, title=None):
""" Plots the trains for a single spiking neuron. """
t_values = [t for t, I, v, u, f in spikes]
v_values = [v for t, I, v, u, f in spikes]
u_values = [u for t, I, v, u, f in spikes]
I_values = [I for t, I, v, u, f in spikes]
f_values = [f for t, I, v, u, f in spikes]
fig = plt.figure()
plt.subplot(4, 1, 1)
plt.ylabel("Potential (mv)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, v_values, "g-")
if title is None:
plt.title("Izhikevich's spiking neuron model")
else:
plt.title("Izhikevich's spiking neuron model ({0!s})".format(title))
plt.subplot(4, 1, 2)
plt.ylabel("Fired")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, f_values, "r-")
plt.subplot(4, 1, 3)
plt.ylabel("Recovery (u)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, u_values, "r-")
plt.subplot(4, 1, 4)
plt.ylabel("Current (I)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, I_values, "r-o")
if filename is not None:
plt.savefig(filename)
if view:
plt.show()
plt.close()
fig = None
return fig
def plot_species(statistics, view=False, filename='speciation.svg'):
""" Visualizes speciation throughout evolution. """
if plt is None:
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
return
species_sizes = statistics.get_species_sizes()
num_generations = len(species_sizes)
curves = np.array(species_sizes).T
fig, ax = plt.subplots()
ax.stackplot(range(num_generations), *curves)
plt.title("Speciation")
plt.ylabel("Size per Species")
plt.xlabel("Generations")
plt.savefig(filename)
if view:
plt.show()
plt.close()
def draw_net(config, genome, view=False, filename='Digraph', node_names=None, show_disabled=True, prune_unused=False,
node_colors=None, fmt='svg',nodes_shape=None):
""" Receives a genome and draws a neural network with arbitrary topology. """
# Attributes for network nodes.
if graphviz is None:
warnings.warn("This display is not available due to a missing optional dependency (graphviz)")
return
print(node_names);
if node_names is None:
node_names = {}
assert type(node_names) is dict
if node_colors is None:
node_colors = {}
assert type(node_colors) is dict
node_attrs = {
'shape': 'circle',
'fontsize': '9',
'height': '0.2',
'width': '0.2'}
dot = graphviz.Digraph(format=fmt, node_attr=node_attrs)
inputs = set();
namedInputs = dict();
for k in config.genome_config.input_keys:
inputs.add(k)
name = node_names.get(k, str(k))
namedInputs[name] = k
print(namedInputs);
input_attrs = {
'style': 'filled',
'shape': 'box',
'fontsize': '9',
'height': '0.2',
'width': '0.2'}
input_attrs['fillcolor'] = node_colors.get(k, 'lightgray')
if (nodes_shape is None):
for name,k in namedInputs.items():
dot.node(name, _attributes=input_attrs)
else:
inGraph = (get_nested_graph(namedInputs,inputs,nodes_shape,fmt,input_attrs));
inGraph.attr(label='Inputs');
dot.subgraph(inGraph);
outputs = set()
outputGraph = graphviz.Digraph(format=fmt,node_attr=node_attrs,graph_attr={'label':'Outputs'},name='cluster');
for k in config.genome_config.output_keys:
outputs.add(k)
name = node_names.get(k, str(k))
node_attrs = {'style': 'filled'}
node_attrs['fillcolor'] = node_colors.get(k, 'lightblue')
node_attrs['tooltip'] = 'bias: {0}, response: {1}'.format(str(genome.nodes[k].bias),str(genome.nodes[k].response));
outputGraph.node(name, _attributes=node_attrs)
dot.subgraph(outputGraph);
if prune_unused:
connections = set()
for cg in genome.connections.values():
if cg.enabled or show_disabled:
connections.add((cg.in_node_id, cg.out_node_id))
used_nodes = copy.copy(outputs)
pending = copy.copy(outputs)
while pending:
new_pending = set()
for a, b in connections:
if b in pending and a not in used_nodes:
new_pending.add(a)
used_nodes.add(a)
pending = new_pending
else:
used_nodes = set(genome.nodes.keys())
for n in used_nodes:
if n in inputs or n in outputs:
continue
attrs = {'style': 'filled',
'fillcolor': node_colors.get(n, 'white')}
attrs['tooltip'] = 'bias: {0}, response: {1}'.format(str(genome.nodes[k].bias),str(genome.nodes[k].response));
dot.node(str(n), _attributes=attrs)
for cg in genome.connections.values():
if cg.enabled or show_disabled:
#if cg.input not in used_nodes or cg.output not in used_nodes:
# continue
input, output = cg.key
a = node_names.get(input, str(input))
b = node_names.get(output, str(output))
constraint = 'true';
if (nodes_shape is not None and True and input in config.genome_config.output_keys):
constraint = 'false'
style = 'solid' if cg.enabled else 'dotted'
color = 'green' if cg.weight > 0 else 'red'
width = str(0.1 + abs(cg.weight / 5.0))
dot.edge(a, b, _attributes={'style': style, 'color': color, 'penwidth': width,'tooltip': 'weight: ' + str(cg.weight),'constraint':constraint})
filepath = os.path.expanduser('~\\Documents\\' + filename + '.gv');
print(filepath)
dot.render(filename=filepath, view=True);
return dot
##def getBlah(namedNodes,nodes,nodes_shape,format,node_attrs,graph_name=""):
## graph = graphviz.Digraph(name='cluster ' + str(graph_name),node_attr=node_attrs);
## for name_shape in nodes_shape:
## if (isinstance(name_shape,tuple)):
## x = 3;
def get_nested_graph(namedNodes,nodes,nodes_shape,format,node_attrs,graph_name=""):
graph = graphviz.Digraph(name='' + str(graph_name),node_attr=node_attrs);
graph.attr(label=str(graph_name));
#print(nodes_shape);
for name_shape in nodes_shape[:-1]:
if (isinstance(name_shape,tuple)):
#print('is tuple: {0}'.format(name_shape));
graph.subgraph(get_nested_graph(namedNodes,nodes,name_shape[1],format,node_attrs,graph_name=name_shape[0]));
else:
#print('is not tuple: {0}'.format(name_shape));
graph.node(str(name_shape));
return graph;