19"""A collection of functions to plot containers using Matplotlib."""
24import matplotlib.pyplot
as plt
25from mpl_toolkits.axes_grid1
import make_axes_locatable
26from functools
import reduce
27from operator
import mul
29from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
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
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.
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.
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)
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:])
65 nbBins = (nbBins[0], 1) + nbBins[1:]
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]
83 figsize = [2.1 + horizNbBinsProd * binSizeInInches, 1. + vertNbBinsProd * binSizeInInches]
86 fig, axes = plt.subplots(nrows=nbBins[1], ncols=nbBins[0], figsize=figsize)
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)
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)
97 fig.subplots_adjust(right=0.85, wspace=0.40)
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])
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)
111 fig.savefig(outputFilename)
118def drawGridInAx(data, ax, cmap, featuresBounds, fitnessBounds, aspect="equal", xlabel = "", ylabel = "", nbBins=None, nbTicks = 5):
120 """Draw a two-axis grid in an existing Matplotlib axes.
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.
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)
134 if vmin == vmax
and cmap.N == 0:
138 cax = ax.imshow(data.T, interpolation=
"none", cmap=cmap, vmin=vmin, vmax=vmax, aspect=aspect)
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
152 if nbBins[0] > nbBins[1]:
154 nbTicksY = int(nbTicksX * nbBins[1] / nbBins[0])
155 elif nbBins[1] > nbBins[0]:
157 nbTicksX = int(nbTicksY * nbBins[0] / nbBins[1])
159 nbTicksX = nbTicksY = nbTicks
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)
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")
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)
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)
189 ax.set_xlabel(xlabel, fontsize=25)
190 ax.set_ylabel(ylabel, fontsize=25)
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.),)
203 nbBins = nbBins + (1,)
204 elif len(data.shape) > 2:
205 raise ValueError(
"plotGrid only supports 1 ou 2-dimensional data.")
209 figsize = [2.1 + 10. * nbBins[0] / (nbBins[0] + nbBins[1]), 1. + 10. * nbBins[1] / (nbBins[0] + nbBins[1])]
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)
219 divider = make_axes_locatable(ax)
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)
227 fig.savefig(outputFilename)
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."""
235 if isinstance(logger, algorithms.AlgorithmLogger):
236 data = logger.evals[key]
241 fig, ax = plt.subplots(figsize=figsize)
245 x = np.arange(len(data))
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)
255 if is_iterable(data[i]):
256 normalised_data[i] = np.array(data[i])
258 normalised_data[i, 0] = data[i]
259 ax.plot(x, normalised_data, color=
'k')
269 plt.xlabel(
"Evaluations", fontsize=14)
272 ylabel_ = ylabel
if ylabel
is not None else key
273 plt.ylabel(ylabel_, fontsize=14)
278 fig.savefig(output_filename)
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."""
286 if isinstance(logger, algorithms.AlgorithmLogger):
287 data = logger.iterations[key]
291 fig, ax = plt.subplots(figsize=figsize)
292 x = np.arange(len(data))
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)
302 if is_iterable(data[i]):
303 normalised_data[i] = np.array(data[i])
305 normalised_data[i, 0] = data[i]
306 ax.plot(x, normalised_data, color=
'k')
311 plt.xlabel(
"Iterations", fontsize=14)
312 ylabel_ = ylabel
if ylabel
is not None else key
313 plt.ylabel(ylabel_, fontsize=14)
315 fig.savefig(output_filename)
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.
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.
326 container = logger.algorithms[0].container
327 if output_dir
is None:
328 output_dir = logger.log_base_path
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")
337 if isinstance(container, containers.Grid):
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)
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)
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)