QDpy
Loading...
Searching...
No Matches
plots.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""A collection of functions to plot containers using Matplotlib."""
20
21
22import os
23import numpy as np
24import matplotlib.pyplot as plt
25from mpl_toolkits.axes_grid1 import make_axes_locatable
26from functools import reduce
27from operator import mul
28
29from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
30
31from qdpy.utils import is_iterable
32from qdpy import containers
33from qdpy import algorithms
34from qdpy._archive_plot import plot_archive, plot_archive_difference, plot_archives, plot_trace_archive
35from qdpy._archive_history import ArchiveFrame, ArchiveRecorder, align_archive_histories, read_archive_history
36from qdpy._archive_animation import animate_archives, assemble_gif, assemble_mp4, render_archive_frames
37from qdpy.lineage import plot_lineage
38
39
40
41
42
43
44
45# TODO refactor name, etc
46def plotGridSubplots(data, outputFilename, cmap, featuresBounds=((0., 1.), (0., 1.), (0., 1.), (0., 1.)), fitnessBounds=(0., 1.), drawCbar = True, xlabel = "", ylabel = "", cBarLabel = "", nbBins = None, nbTicks = None, binSizeInInches = 0.30):
47 """Save a grid plot for up to four descriptor axes.
48
49 One- and two-axis data use a single panel. Additional axes index
50 the subplot arrangement. Pass a scalar objective slice such as
51 ``grid.quality_array[..., 0]`` when plotting multiobjective fitness.
52 """
53 # Verify data dimension is supported by this funtion
54 if len(data.shape) > 4:
55 raise ValueError("plotGridSubplots only supports up to 4 dimensions.")
56 elif len(data.shape) <= 2:
57 plotGrid(data, outputFilename, cmap, featuresBounds=featuresBounds, fitnessBounds=fitnessBounds, drawCbar=drawCbar, xlabel=xlabel, ylabel=ylabel, cBarLabel=cBarLabel, nbBins=nbBins, nbTicks=nbTicks)
58 return
59
60 # Verify dimension is even
61 if len(data.shape) % 2 == 1:
62 data = data.reshape((data.shape[0], 1) + data.shape[1:])
63 featuresBounds = (featuresBounds[0], (0., 0.)) + tuple(featuresBounds[1:])
64 if nbBins != None:
65 nbBins = (nbBins[0], 1) + nbBins[1:]
66 if not nbBins:
67 nbBins = data.shape
68
69 #data[0,:,:,:] = np.linspace(0., 1., nbBins[1] * nbBins[2] * nbBins[3]).reshape((nbBins[1], nbBins[2], nbBins[3]))
70
71 # Compute figure infos from nbBins
72 horizNbBins = nbBins[::2]
73 horizNbBinsProd = reduce(mul, horizNbBins, 1)
74 vertNbBins = nbBins[1::2]
75 vertNbBinsProd = reduce(mul, vertNbBins, 1)
76 totProp = horizNbBinsProd + vertNbBinsProd
77 upperlevelTot = nbBins[0] + nbBins[1]
78
79 # Determine figure size from nbBins infos
80 #figsize = [2.1 + 10. * horizNbBinsProd / upperlevelTot, 1. + 10. * vertNbBinsProd / upperlevelTot]
81 #if figsize[1] < 2:
82 # figsize[1] = 2.
83 figsize = [2.1 + horizNbBinsProd * binSizeInInches, 1. + vertNbBinsProd * binSizeInInches]
84
85 # Create figure
86 fig, axes = plt.subplots(nrows=nbBins[1], ncols=nbBins[0], figsize=figsize)
87
88 # Create subplots
89 for x in range(nbBins[0]):
90 for y in range(nbBins[1]):
91 ax = plt.subplot(nbBins[1], nbBins[0], (nbBins[1] - y - 1) * nbBins[0] + x + 1)
92 #ax = axes[x,y]
93 cax = drawGridInAx(data[x, y, 0:nbBins[2], 0:nbBins[3]], ax, cmap=cmap, featuresBounds=featuresBounds[-2:], fitnessBounds=fitnessBounds[-2:], aspect="equal", xlabel=xlabel, ylabel=ylabel, nbBins=(nbBins[2], nbBins[3]), nbTicks=nbTicks)
94
95 plt.tight_layout()
96 if drawCbar:
97 fig.subplots_adjust(right=0.85, wspace=0.40)
98 #cbarAx = fig.add_axes([0.90, 0.15, 0.01, 0.7])
99 if figsize[0] < 4.:
100 cbarAx = fig.add_axes([0.75, 0.15, 0.02, 0.7])
101 elif figsize[0] < 6.:
102 cbarAx = fig.add_axes([0.80, 0.15, 0.02, 0.7])
103 elif figsize[0] < 10.:
104 cbarAx = fig.add_axes([0.85, 0.15, 0.02, 0.7])
105 else:
106 cbarAx = fig.add_axes([0.90, 0.15, 0.02, 0.7])
107 cbar = fig.colorbar(cax, cax=cbarAx, format="%.2f")
108 cbar.ax.tick_params(labelsize=20)
109 cbar.ax.set_ylabel(cBarLabel, fontsize=22)
110
111 fig.savefig(outputFilename)
112
113
114
115
116
117# TODO refactor name, etc
118def drawGridInAx(data, ax, cmap, featuresBounds, fitnessBounds, aspect="equal", xlabel = "", ylabel = "", nbBins=None, nbTicks = 5):
119 # Determine bounds
120 """Draw a two-axis grid in an existing Matplotlib axes.
121
122 Position the descriptor labels at grid boundaries and use the
123 supplied fitness range for colour normalisation. Return the image
124 artist so callers can attach a colour bar.
125 """
126 vmin = fitnessBounds[0]
127 if np.isnan(vmin) or np.isinf(vmin):
128 vmin = np.nanmin(data)
129 vmax = fitnessBounds[1]
130 if np.isnan(vmax) or np.isinf(vmax):
131 vmax = np.nanmax(data)
132
133 # Fix cmap if data is a null matrix
134 if vmin == vmax and cmap.N == 0:
135 cmap.N = 1
136
137 # Draw grid
138 cax = ax.imshow(data.T, interpolation="none", cmap=cmap, vmin=vmin, vmax=vmax, aspect=aspect)
139 ax.invert_yaxis()
140
141 # Define the number of ticks on x,y axis
142 if is_iterable(nbTicks):
143 if len(nbTicks) != 2:
144 raise ValueError("nbTicks can be None, an Integer or a Sequence of size 2.")
145 nbTicksX, nbTicksY = nbTicks
146 elif nbTicks == None:
147 nbTicksX = round(pow(nbBins[0], 1./2.))
148 nbTicksX = nbTicksX if nbTicksX % 2 == 0 else nbTicksX + 1
149 nbTicksY = round(pow(nbBins[1], 1./2.))
150 nbTicksY = nbTicksY if nbTicksY % 2 == 0 else nbTicksY + 1
151 else:
152 if nbBins[0] > nbBins[1]:
153 nbTicksX = nbTicks
154 nbTicksY = int(nbTicksX * nbBins[1] / nbBins[0])
155 elif nbBins[1] > nbBins[0]:
156 nbTicksY = nbTicks
157 nbTicksX = int(nbTicksY * nbBins[0] / nbBins[1])
158 else:
159 nbTicksX = nbTicksY = nbTicks
160 # Verify than the number of ticks is valid
161 if nbTicksX > nbBins[0] or nbTicksX < 1:
162 nbTicksX = min(nbBins[0], nbTicks)
163 if nbTicksY > nbBins[1] or nbTicksY < 1:
164 nbTicksY = min(nbBins[1], nbTicks)
165
166 # Set ticks
167 ax.xaxis.set_tick_params(which='major', left=True, bottom=True, top=False, right=False)
168 ax.yaxis.set_tick_params(which='major', left=True, bottom=True, top=False, right=False)
169 if len(featuresBounds) > 1:
170 xticks = np.linspace(-0.5, data.shape[0] - 0.5, nbTicksX + 1)
171 xlabels = np.linspace(*featuresBounds[0], nbTicksX + 1).round(2)
172 ax.set_xticks(xticks, labels=xlabels, fontsize=22, rotation="vertical")
173 else:
174 ax.set_xticks([])
175 if nbBins[1] == 1:
176 ax.set_yticks([])
177 else:
178 yticks = np.linspace(-0.5, data.shape[1] - 0.5, nbTicksY + 1)
179 ylabels = np.linspace(*featuresBounds[-1], nbTicksY + 1).round(2)
180 ax.set_yticks(yticks, labels=ylabels, fontsize=22)
181
182 # Draw grid
183 ax.xaxis.set_tick_params(which='minor', direction="in", left=False, bottom=False, top=False, right=False)
184 ax.yaxis.set_tick_params(which='minor', direction="in", left=False, bottom=False, top=False, right=False)
185 ax.set_xticks(np.arange(-.5, data.shape[0], 1), minor=True)
186 ax.set_yticks(np.arange(-.5, data.shape[1], 1), minor=True)
187 #ax.grid(which='minor', color=(0.8,0.8,0.8,0.5), linestyle='-', linewidth=0.1)
188
189 ax.set_xlabel(xlabel, fontsize=25)
190 ax.set_ylabel(ylabel, fontsize=25)
191 ax.autoscale_view()
192 return cax
193
194
195
196# TODO refactor name, etc
197def plotGrid(data, outputFilename, cmap, featuresBounds=[(0., 1.), (0., 1.)], fitnessBounds=(0., 1.), drawCbar = True, xlabel = "", ylabel = "", cBarLabel = "", nbBins = None, nbTicks = None):
198 """Save a one- or two-axis grid to a file with optional colour bar and descriptor labels."""
199 if len(data.shape) == 1:
200 data = data.reshape((data.shape[0], 1))
201 featuresBounds = tuple(featuresBounds) + ((0., 0.),)
202 if nbBins != None:
203 nbBins = nbBins + (1,)
204 elif len(data.shape) > 2:
205 raise ValueError("plotGrid only supports 1 ou 2-dimensional data.")
206 if not nbBins:
207 nbBins = data.shape
208
209 figsize = [2.1 + 10. * nbBins[0] / (nbBins[0] + nbBins[1]), 1. + 10. * nbBins[1] / (nbBins[0] + nbBins[1])]
210 aspect = "equal"
211 if figsize[1] < 2:
212 figsize[1] = 2.
213 aspect = "auto"
214
215 fig, ax = plt.subplots(figsize=figsize)
216 cax = drawGridInAx(data, ax, cmap=cmap, featuresBounds=featuresBounds, fitnessBounds=fitnessBounds, aspect=aspect, xlabel=xlabel, ylabel=ylabel, nbBins=nbBins, nbTicks=nbTicks)
217
218 if drawCbar:
219 divider = make_axes_locatable(ax)
220 #cax2 = divider.append_axes("right", size="5%", pad=0.15)
221 cax2 = divider.append_axes("right", size=0.5, pad=0.15)
222 cbar = fig.colorbar(cax, cax=cax2, format="%.2f")
223 cbar.ax.tick_params(labelsize=22)
224 cbar.ax.set_ylabel(cBarLabel, fontsize=24)
225
226 plt.tight_layout()
227 fig.savefig(outputFilename)
228
229
230
231
232def plot_evals(logger, output_filename, key="max", ylim=None, ylabel=None, figsize=(4., 4.)):
233 """Save one or more series from the logger's evaluation table."""
234 # Retrieve evaluation data for key `key`
235 if isinstance(logger, algorithms.AlgorithmLogger):
236 data = logger.evals[key]
237 else:
238 data = logger
239 #print(data)
240
241 fig, ax = plt.subplots(figsize=figsize)
242 #ax = fig.add_subplot(111)
243 #fig.subplots_adjust(bottom=0.3)
244
245 x = np.arange(len(data))
246
247 # Normalise data
248 tmp_shape = 1
249 for i in x:
250 if is_iterable(data[i]):
251 tmp_shape = max(tmp_shape, len(data[i]))
252 data_shape = (len(data), tmp_shape)
253 normalised_data = np.zeros(data_shape)
254 for i in x:
255 if is_iterable(data[i]):
256 normalised_data[i] = np.array(data[i])
257 else:
258 normalised_data[i, 0] = data[i]
259 ax.plot(x, normalised_data, color='k')
260
261 if ylim is not None:
262 ax.set_ylim(ylim)
263
264 #x = np.arange(0, nb_iterations+1, 25)
265 #if len(x) > 4:
266 # x = x[::2]
267 #tsplot(ax, data, color='k')
268 #ax.set_ylim([0., 1.])
269 plt.xlabel("Evaluations", fontsize=14)
270 #plt.xticks(x, fontsize=18)
271 #ax.set_xticklabels([str(i * args.nbEvalsPerIt) for i in x])
272 ylabel_ = ylabel if ylabel is not None else key
273 plt.ylabel(ylabel_, fontsize=14)
274 #plt.yticks(fontsize=18)
275 #sns.despine()
276 #plt.tight_layout(rect=[0, 0, 1.0, 0.95])
277 plt.tight_layout()
278 fig.savefig(output_filename)
279 plt.close(fig)
280
281
282
283def plot_iterations(logger, output_filename, key="max", ylim=None, ylabel=None, figsize=(4., 4.)):
284 """Save one or more series from the logger's iteration table."""
285 # Retrieve evaluation data for key `key`
286 if isinstance(logger, algorithms.AlgorithmLogger):
287 data = logger.iterations[key]
288 else:
289 data = logger
290
291 fig, ax = plt.subplots(figsize=figsize)
292 x = np.arange(len(data))
293
294 # Normalise data
295 tmp_shape = 1
296 for i in x:
297 if is_iterable(data[i]):
298 tmp_shape = max(tmp_shape, len(data[i]))
299 data_shape = (len(data), tmp_shape)
300 normalised_data = np.zeros(data_shape)
301 for i in x:
302 if is_iterable(data[i]):
303 normalised_data[i] = np.array(data[i])
304 else:
305 normalised_data[i, 0] = data[i]
306 ax.plot(x, normalised_data, color='k')
307
308 if ylim is not None:
309 ax.set_ylim(ylim)
310
311 plt.xlabel("Iterations", fontsize=14)
312 ylabel_ = ylabel if ylabel is not None else key
313 plt.ylabel(ylabel_, fontsize=14)
314 plt.tight_layout()
315 fig.savefig(output_filename)
316 plt.close(fig)
317
318
319def default_plots_grid(logger, output_dir=None, suffix=None, to_grid_parameters={}, fitness_domain=None):
320 """Save the primary optimiser's evaluation, iteration, quality, and activity plots.
321
322 Use the existing Grid, or convert a container using
323 ``to_grid_parameters``. The fitness surface shows the first objective.
324 The destination directory defaults to the logger's output directory.
325 """
326 container = logger.algorithms[0].container # XXX
327 if output_dir is None:
328 output_dir = logger.log_base_path
329 if suffix == None:
330 suffix = ""
331
332 plot_evals(logger, os.path.join(output_dir, f"./evals_fitnessmax0{suffix}.pdf"), "max0", ylabel="Fitness")
333 ylim_contsize = (0, len(container)) if np.isinf(container.capacity) else (0, container.capacity)
334 plot_evals(logger, os.path.join(output_dir, f"./evals_contsize{suffix}.pdf"), "cont_size", ylim=ylim_contsize, ylabel="Container size")
335 plot_iterations(logger, os.path.join(output_dir, f"./iterations_nbupdated{suffix}.pdf"), "nb_updated", ylabel="Number of updated bins")
336
337 if isinstance(container, containers.Grid):
338 grid = container
339 else:
340 if 'shape' not in to_grid_parameters:
341 to_grid_parameters['shape'] = (32,) * len(container.features_domain)
342 grid = container.to_grid(**to_grid_parameters)
343
344 plot_path = os.path.join(output_dir, f"performancesGrid{suffix}.pdf")
345 cmap_perf = "inferno" if logger.algorithms[0].optimisation_task == "maximisation" else "inferno_r"
346 fitness_domain = grid.fitness_domain if fitness_domain is None else fitness_domain
347 plotGridSubplots(grid.quality_array[... ,0], plot_path, plt.get_cmap(cmap_perf), grid.features_domain, fitness_domain[0], nbTicks=None)
348
349 plot_path = os.path.join(output_dir, f"activityGrid{suffix}.pdf")
350 max_activity = np.max(grid.activity_per_bin)
351 plotGridSubplots(grid.activity_per_bin, plot_path, plt.get_cmap("Reds", max_activity+1), grid.features_domain, [0, max_activity], nbTicks=None)
352
353
354
355# MODELINE "{{{1
356# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
357# vim:foldmethod=marker