1+ from __future__ import print_function
2+
3+ import copy
4+ import warnings
5+
6+ import graphviz
7+ import matplotlib .pyplot as plt
8+ import numpy as np
9+
10+
11+ def plot_stats (statistics , ylog = False , view = False , filename = 'avg_fitness.svg' ):
12+ """ Plots the population's average and best fitness. """
13+ if plt is None :
14+ warnings .warn ("This display is not available due to a missing optional dependency (matplotlib)" )
15+ return
16+
17+ generation = range (len (statistics .most_fit_genomes ))
18+ best_fitness = [c .fitness for c in statistics .most_fit_genomes ]
19+ avg_fitness = np .array (statistics .get_fitness_mean ())
20+ stdev_fitness = np .array (statistics .get_fitness_stdev ())
21+
22+ plt .plot (generation , avg_fitness , 'b-' , label = "average" )
23+ plt .plot (generation , avg_fitness - stdev_fitness , 'g-.' , label = "-1 sd" )
24+ plt .plot (generation , avg_fitness + stdev_fitness , 'g-.' , label = "+1 sd" )
25+ plt .plot (generation , best_fitness , 'r-' , label = "best" )
26+
27+ plt .title ("Population's average and best fitness" )
28+ plt .xlabel ("Generations" )
29+ plt .ylabel ("Fitness" )
30+ plt .grid ()
31+ plt .legend (loc = "best" )
32+ if ylog :
33+ plt .gca ().set_yscale ('symlog' )
34+
35+ plt .savefig (filename )
36+ if view :
37+ plt .show ()
38+
39+ plt .close ()
40+
41+
42+ def plot_spikes (spikes , view = False , filename = None , title = None ):
43+ """ Plots the trains for a single spiking neuron. """
44+ t_values = [t for t , I , v , u , f in spikes ]
45+ v_values = [v for t , I , v , u , f in spikes ]
46+ u_values = [u for t , I , v , u , f in spikes ]
47+ I_values = [I for t , I , v , u , f in spikes ]
48+ f_values = [f for t , I , v , u , f in spikes ]
49+
50+ fig = plt .figure ()
51+ plt .subplot (4 , 1 , 1 )
52+ plt .ylabel ("Potential (mv)" )
53+ plt .xlabel ("Time (in ms)" )
54+ plt .grid ()
55+ plt .plot (t_values , v_values , "g-" )
56+
57+ if title is None :
58+ plt .title ("Izhikevich's spiking neuron model" )
59+ else :
60+ plt .title ("Izhikevich's spiking neuron model ({0!s})" .format (title ))
61+
62+ plt .subplot (4 , 1 , 2 )
63+ plt .ylabel ("Fired" )
64+ plt .xlabel ("Time (in ms)" )
65+ plt .grid ()
66+ plt .plot (t_values , f_values , "r-" )
67+
68+ plt .subplot (4 , 1 , 3 )
69+ plt .ylabel ("Recovery (u)" )
70+ plt .xlabel ("Time (in ms)" )
71+ plt .grid ()
72+ plt .plot (t_values , u_values , "r-" )
73+
74+ plt .subplot (4 , 1 , 4 )
75+ plt .ylabel ("Current (I)" )
76+ plt .xlabel ("Time (in ms)" )
77+ plt .grid ()
78+ plt .plot (t_values , I_values , "r-o" )
79+
80+ if filename is not None :
81+ plt .savefig (filename )
82+
83+ if view :
84+ plt .show ()
85+ plt .close ()
86+ fig = None
87+
88+ return fig
89+
90+
91+ def plot_species (statistics , view = False , filename = 'speciation.svg' ):
92+ """ Visualizes speciation throughout evolution. """
93+ if plt is None :
94+ warnings .warn ("This display is not available due to a missing optional dependency (matplotlib)" )
95+ return
96+
97+ species_sizes = statistics .get_species_sizes ()
98+ num_generations = len (species_sizes )
99+ curves = np .array (species_sizes ).T
100+
101+ fig , ax = plt .subplots ()
102+ ax .stackplot (range (num_generations ), * curves )
103+
104+ plt .title ("Speciation" )
105+ plt .ylabel ("Size per Species" )
106+ plt .xlabel ("Generations" )
107+
108+ plt .savefig (filename )
109+
110+ if view :
111+ plt .show ()
112+
113+ plt .close ()
114+
115+
116+ def draw_net (config , genome , view = False , filename = None , node_names = None , show_disabled = True , prune_unused = False ,
117+ node_colors = None , fmt = 'svg' ):
118+ """ Receives a genome and draws a neural network with arbitrary topology. """
119+ # Attributes for network nodes.
120+ if graphviz is None :
121+ warnings .warn ("This display is not available due to a missing optional dependency (graphviz)" )
122+ return
123+
124+ if node_names is None :
125+ node_names = {}
126+
127+ assert type (node_names ) is dict
128+
129+ if node_colors is None :
130+ node_colors = {}
131+
132+ assert type (node_colors ) is dict
133+
134+ node_attrs = {
135+ 'shape' : 'circle' ,
136+ 'fontsize' : '9' ,
137+ 'height' : '0.2' ,
138+ 'width' : '0.2' }
139+
140+ dot = graphviz .Digraph (format = fmt , node_attr = node_attrs )
141+
142+ inputs = set ()
143+ for k in config .genome_config .input_keys :
144+ inputs .add (k )
145+ name = node_names .get (k , str (k ))
146+ input_attrs = {'style' : 'filled' ,
147+ 'shape' : 'box' }
148+ input_attrs ['fillcolor' ] = node_colors .get (k , 'lightgray' )
149+ dot .node (name , _attributes = input_attrs )
150+
151+ outputs = set ()
152+ for k in config .genome_config .output_keys :
153+ outputs .add (k )
154+ name = node_names .get (k , str (k ))
155+ node_attrs = {'style' : 'filled' }
156+ node_attrs ['fillcolor' ] = node_colors .get (k , 'lightblue' )
157+
158+ dot .node (name , _attributes = node_attrs )
159+
160+ if prune_unused :
161+ connections = set ()
162+ for cg in genome .connections .values ():
163+ if cg .enabled or show_disabled :
164+ connections .add ((cg .in_node_id , cg .out_node_id ))
165+
166+ used_nodes = copy .copy (outputs )
167+ pending = copy .copy (outputs )
168+ while pending :
169+ new_pending = set ()
170+ for a , b in connections :
171+ if b in pending and a not in used_nodes :
172+ new_pending .add (a )
173+ used_nodes .add (a )
174+ pending = new_pending
175+ else :
176+ used_nodes = set (genome .nodes .keys ())
177+
178+ for n in used_nodes :
179+ if n in inputs or n in outputs :
180+ continue
181+
182+ attrs = {'style' : 'filled' ,
183+ 'fillcolor' : node_colors .get (n , 'white' )}
184+ dot .node (str (n ), _attributes = attrs )
185+
186+ for cg in genome .connections .values ():
187+ if cg .enabled or show_disabled :
188+ #if cg.input not in used_nodes or cg.output not in used_nodes:
189+ # continue
190+ input , output = cg .key
191+ a = node_names .get (input , str (input ))
192+ b = node_names .get (output , str (output ))
193+ style = 'solid' if cg .enabled else 'dotted'
194+ color = 'green' if cg .weight > 0 else 'red'
195+ width = str (0.1 + abs (cg .weight / 5.0 ))
196+ dot .edge (a , b , _attributes = {'style' : style , 'color' : color , 'penwidth' : width })
197+
198+ dot .render (filename , view = view )
199+
200+ return dot
0 commit comments