QDpy
Loading...
Searching...
No Matches
_archive_animation.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Render comparable archive frames and encode GIF or MP4 animations."""
6
7from dataclasses import replace
8from math import ceil, fsum, isfinite, prod, sqrt
9from os import PathLike, replace as replace_file
10from pathlib import Path
11import re
12import shutil
13import subprocess
14from tempfile import TemporaryDirectory
15import warnings
16
17import matplotlib as mpl
18import matplotlib.pyplot as plt
19import numpy as np
20from PIL import Image
21
22from ._archive_comparison import _cell_bests, _cell_geometry
23from ._archive_data import _named_data
24from ._archive_history import _history_inputs, read_archive_history
25from ._archive_plot import _colour_limits, _finite_extent, _plot_panels, _prepare_panel
26from .base import _atomic_output_path
27
28__all__ = ["render_archive_frames", "assemble_gif", "assemble_mp4", "animate_archives"]
29
30
31def _panel_settings(name, defaults, panel_options):
32 return defaults | panel_options.get(name, {})
33
34
35def _union(left, right):
36 if not left or not right:
37 return left or right
38 return min(left[0], right[0]), max(left[1], right[1])
39
40
41def _scan_history(inputs, trusted_pickle, defaults, panel_options, shared_scale, show_progress):
42 # Keep one layout template per archive and only extrema for later frames.
43 templates = {}
44 extents = {}
45 values = {}
46 empty = {}
47 trends = {}
48 last_budget = 0
49 for frame in read_archive_history(inputs, trusted_pickle=trusted_pickle):
50 if show_progress:
51 if frame.evaluations is None or frame.evaluations < last_budget:
52 raise ValueError("Progress curves need nondecreasing evaluation counts on every frame.")
53 last_budget = frame.evaluations
54 for name, archive in _named_data(frame.archives).items():
55 if show_progress:
56 objective = _panel_settings(name, defaults, panel_options).get("objective", 0)
57 trends.setdefault(name, []).append((frame.evaluations, *_progress_metrics(archive, objective)))
58 templates.setdefault(name, None)
59 if not archive.dimension:
60 empty.setdefault(name, archive)
61 continue
62 panel = _prepare_panel(archive, **_panel_settings(name, defaults, panel_options))
63 if templates[name] is None:
64 templates[name] = panel
65 extents[name] = panel.limits
66 elif templates[name].dimensions != panel.dimensions:
67 raise ValueError(f"Descriptor axes changed for panel {name!r}. Set dimensions explicitly.")
68 else:
69 extents[name] = tuple(_union(a, b) for a, b in zip(extents[name], panel.limits))
70 colour_range = _union(panel.hint, _finite_extent(panel.values))
71 values[name] = _union(values.get(name, ()), colour_range)
72 if set(panel_options) - set(templates):
73 raise ValueError("Panel options must use an archive label.")
74 for name, template in templates.items():
75 if template is None:
76 template = _prepare_panel(empty[name], **_panel_settings(name, defaults, panel_options))
77 templates[name] = template
78 extents[name] = template.limits
79 values[name] = template.hint
80 bounds = {name: replace(template, hint=values[name], values=np.empty(0))
81 for name, template in templates.items()}
82 shared = _colour_limits(list(bounds.values())) if shared_scale else None
83 scales = {name: shared or _colour_limits([panel]) for name, panel in bounds.items()}
84 return templates, scales, extents, trends
85
86
87def _progress_metrics(archive, objective):
88 """Sum the selected objective's normalized cell bests and count occupied cells."""
89 occupied = {entry.cell for entry in archive.entries if entry.cell is not None}
90 coverage = len(occupied) / prod(archive.shape) if archive.shape else np.nan
91 if not 0 <= objective < len(archive.fitness_domain):
92 return np.nan, coverage
93 if not archive.entries:
94 return 0., coverage
95 low, high = archive.fitness_domain[objective]
96 if not isfinite(low) or not isfinite(high):
97 return np.nan, coverage
98 if archive.shape:
99 values = _cell_bests(archive, objective).values()
100 else:
101 values = ((entry.fitness[objective], entry.fitness_weights[objective]) for entry in archive.entries)
102 score = fsum((high - raw if weight < 0 else raw - low) / (high - low or 1.)
103 for raw, weight in values if isfinite(raw))
104 return score, coverage
105
106
107def _draw_progress(fig, trends, evaluations, bottom):
108 for coordinate, title, metric in ((.10, "Normalized QD score", 1), (.55, "Coverage", 2)):
109 ax = fig.add_axes((coordinate, .075, .35, bottom - .163))
110 for label, points in trends.items():
111 ax.step([row[0] for row in points], [row[metric] for row in points], where="post",
112 label=label, linewidth=1.4)
113 ax.axvline(evaluations, color="#394759", linestyle="--", linewidth=1)
114 ax.set_title(title, fontsize=10)
115 ax.set_xlabel("Evaluations")
116 ax.grid(alpha=.22)
117 if metric == 1 and len(trends) > 1:
118 ax.legend(loc="best", fontsize=7, frameon=False)
119
120
121def _highlight_cells(ax, panel, previous, objective):
122 data = panel.archive
123 if (previous is None or panel.view not in ("grid", "cvt") or panel.section
124 or _cell_geometry(data) != _cell_geometry(previous)):
125 return
126 old, new = _cell_bests(previous, objective), _cell_bests(data, objective)
127 filled, improved = [], []
128 edges = data.bin_edges
129 if not data.centroids and not edges:
130 edges = tuple(np.linspace(*bounds, bins + 1) for bounds, bins in zip(data.descriptor_domain, data.shape))
131 for cell, (raw, direction) in new.items():
132 if cell in old and (old[cell][1] != direction or (raw - old[cell][0]) * direction <= 0):
133 continue
134 if data.centroids:
135 position = [data.centroids[cell[0]][axis] for axis in panel.dimensions]
136 else:
137 position = [(edges[axis][cell[axis]] + edges[axis][cell[axis] + 1]) / 2 for axis in panel.dimensions]
138 if len(position) == 1:
139 position.append(.5)
140 (improved if cell in old else filled).append(position)
141 for points, marker, label in ((filled, "o", "New cell"), (improved, "^", "Improved")):
142 if points:
143 ax.scatter(*zip(*points), marker=marker, s=42, facecolors="#ffffff", edgecolors="#172638",
144 linewidth=.8, label=label, zorder=4)
145 if filled or improved:
146 ax.legend(loc="upper right", fontsize=7, framealpha=.9)
147
148
149def _title(frame):
150 detail = []
151 if frame.iteration is not None:
152 detail.append(f"Iteration {frame.iteration}")
153 if frame.evaluations is not None:
154 detail.append(f"{frame.evaluations:,} evaluations")
155 return " ยท ".join(detail) or f"Frame {frame.number}"
156
157
158
159def render_archive_frames(source, output_dir, *, trusted_pickle=False, panel_options=None,
160 shared_scale=False, columns=None, colorbar=True, figsize=None, dpi=100,
161 show_progress=False, highlight_changes=False, **options):
162 """Write numbered PNG frames and return their paths in time order.
163
164 Use a history directory or the same input accepted by
165 ``read_archive_history()``. View options follow ``plot_archives()``.
166 Axis and colour limits are gathered across the history before drawing.
167 The output directory must be new or empty.
168
169 :param show_progress: Add QD score and coverage curves with a budget cursor.
170 :param highlight_changes: Mark new and improved cells on stable planar geometry.
171 """
172 if not isfinite(dpi) or dpi <= 0:
173 raise ValueError("dpi must be positive and finite.")
174 inputs = _history_inputs(source)
175 panel_options = panel_options or {}
176 templates, scales, limits, trends = _scan_history(
177 inputs, trusted_pickle, options, panel_options, shared_scale, show_progress,
178 )
179 bottom = None
180 if show_progress:
181 columns = min(len(templates), ceil(sqrt(len(templates)))) if columns is None else columns
182 if columns < 1:
183 raise ValueError("columns must be positive.")
184 figsize = figsize or (max(7., 4.3 * columns), 3.7 * ceil(len(templates) / columns) + 2.2)
185 bottom = max(.21, min(.48, 2.1 / figsize[1]))
186 directory = Path(output_dir)
187 directory.mkdir(parents=True, exist_ok=True)
188 if any(directory.iterdir()):
189 raise FileExistsError(f"Frame output directory must be empty: {directory}")
190 paths = []
191 previous = {}
192 for number, frame in enumerate(read_archive_history(inputs, trusted_pickle=trusted_pickle)):
193 panels = {}
194 for name, archive in _named_data(frame.archives).items():
195 settings = _panel_settings(name, options, panel_options)
196 settings["dimensions"] = templates[name].dimensions
197 panels[name] = _prepare_panel(archive, **settings)
198 fig, axes = _plot_panels(panels, columns=columns, shared_scale=shared_scale, colorbar=colorbar,
199 figsize=figsize, templates=templates, scales=scales, limits=limits, bottom=bottom)
200 path = directory / f"frame-{number:06d}.png"
201 try:
202 fig.suptitle(_title(frame))
203 if show_progress:
204 _draw_progress(fig, trends, frame.evaluations, bottom)
205 if highlight_changes:
206 for name, panel in panels.items():
207 objective = _panel_settings(name, options, panel_options).get("objective", 0)
208 _highlight_cells(axes[name], panel, previous.get(name), objective)
209 previous = {name: panel.archive for name, panel in panels.items()}
210 with _atomic_output_path(path) as temporary, mpl.rc_context({"savefig.bbox": None}):
211 fig.savefig(temporary, format="png", dpi=dpi)
212 finally:
213 plt.close(fig)
214 paths.append(path)
215 return tuple(paths)
216
217
218def _natural_key(path):
219 return [int(token) if i % 2 else token.casefold()
220 for i, token in enumerate(re.split(r"(\d+)", path.name))], path.name
221
222
223def _png_inputs(frames):
224 if isinstance(frames, (str, PathLike)):
225 path = Path(frames)
226 files = sorted((p for p in path.iterdir() if p.is_file() and p.suffix.lower() == ".png"),
227 key=_natural_key) if path.is_dir() else [path]
228 else:
229 files = list(map(Path, frames))
230 if not files:
231 raise ValueError("Provide at least one PNG frame.")
232 size = None
233 for path in files:
234 with Image.open(path) as image:
235 if image.format != "PNG":
236 raise ValueError(f"Expected a PNG frame: {path}")
237 if size is not None and image.size != size:
238 raise ValueError("PNG frames must have identical pixel dimensions.")
239 size = image.size
240 image.verify()
241 return [path.resolve() for path in files]
242
243
244def _process(args):
245 proc = subprocess.run(args, check=False, capture_output=True, text=True, errors="replace")
246 if proc.returncode:
247 reason = proc.stderr.strip() or proc.stdout.strip() or f"exit status {proc.returncode}"
248 raise RuntimeError(reason)
249
250
251def _ffmpeg_inputs(executable, frames, folder, fps):
252 """Stage a contiguous image sequence for explicit or nonstandard frame names."""
253 folder.mkdir()
254 for number, frame in enumerate(frames):
255 shutil.copyfile(frame, folder / f"frame-{number:06d}.png")
256 return [executable, "-hide_banner", "-loglevel", "error", "-y", "-filter_threads", "1",
257 "-filter_complex_threads", "1", "-framerate", str(fps), "-start_number", "0",
258 "-i", str(folder / "frame-%06d.png")]
259
260
261def _encode(name, executable, frames, output, fps):
262 if name == "gifski":
263 _process([executable, "--no-sort", "--fps", str(fps), "--repeat", "0",
264 "--output", str(output), *map(str, frames)])
265 elif name == "ffmpeg":
266 staged = output.parent / "ffmpeg"
267 palette = staged / "palette.png"
268 common = _ffmpeg_inputs(executable, frames, staged, fps)
269 _process([*common, "-vf", "palettegen", "-frames:v", "1", str(palette)])
270 _process([*common, "-i", str(palette), "-lavfi", "paletteuse", "-loop", "0", str(output)])
271 else:
272 images = []
273 for path in frames:
274 with Image.open(path) as image:
275 images.append(image.convert("RGBA"))
276 # GIF stores centiseconds. Round cumulative frame timings to avoid drift.
277 durations = [10 * (round((n + 1) * 100 / fps) - round(n * 100 / fps)) for n in range(len(images))]
278 images[0].save(output, format="GIF", save_all=True, append_images=images[1:], duration=durations, loop=0)
279
280
281def _encoders(encoder):
282 order = ("gifski", "ffmpeg", "pillow")
283 if encoder != "auto" and encoder not in order:
284 raise ValueError("Choose encoder='auto', 'gifski', 'ffmpeg', or 'pillow'.")
285 for name in order if encoder == "auto" else (encoder,):
286 executable = shutil.which(name) if name != "pillow" else None
287 if name == "pillow" or executable:
288 yield name, executable
289 elif encoder != "auto":
290 raise RuntimeError(f"{name} is unavailable on PATH.")
291
292
293
294def assemble_gif(frames, output, *, fps=8, encoder="auto", overwrite=False):
295 """Encode looping GIF output and return its path.
296
297 Directories use natural filename order. Explicit sequences keep the
298 caller's order. Auto mode tries gifski, FFmpeg, and Pillow in sequence.
299 Explicit encoder failures report the original diagnostic.
300 """
301 destination = Path(output).absolute()
302 if not isfinite(fps) or not 0 < fps <= 100:
303 raise ValueError("fps must be in (0, 100] to fit GIF's centisecond timing.")
304 if destination.exists() and not overwrite:
305 raise FileExistsError(destination)
306 frames = _png_inputs(frames)
307 destination.parent.mkdir(parents=True, exist_ok=True)
308 failures = []
309 with TemporaryDirectory(prefix=".qdpy-gif-", dir=destination.parent) as directory:
310 for name, executable in _encoders(encoder):
311 pending = Path(directory) / f"{name}.gif"
312 try:
313 _encode(name, executable, frames, pending, fps)
314 with Image.open(pending) as image:
315 if image.format != "GIF" or not image.n_frames:
316 raise RuntimeError("Encoder did not write a readable GIF.")
317 except (OSError, RuntimeError, ValueError) as error:
318 detail = f"{name} failed: {error}"
319 if encoder != "auto":
320 raise RuntimeError(detail) from error
321 failures.append(detail)
322 warnings.warn(detail, RuntimeWarning, stacklevel=2)
323 continue
324 if overwrite:
325 replace_file(pending, destination)
326 else:
327 # Atomically publish without overwriting a concurrently created file.
328 destination.hardlink_to(pending)
329 return Path(output)
330 raise RuntimeError("Unable to encode GIF. " + "\n".join(failures))
331
332
333
334def assemble_mp4(frames, output, *, fps=8, overwrite=False):
335 """Encode a silent MP4 with the system FFmpeg and return the output path.
336
337 Directories use natural filename order and explicit sequences retain
338 caller order. Frames with odd dimensions are padded to even dimensions.
339 """
340 destination = Path(output).absolute()
341 if not isfinite(fps) or fps <= 0:
342 raise ValueError("fps must be positive and finite.")
343 if destination.exists() and not overwrite:
344 raise FileExistsError(destination)
345 executable = shutil.which("ffmpeg")
346 if executable is None:
347 raise RuntimeError("MP4 export requires ffmpeg on PATH.")
348 frames = _png_inputs(frames)
349 destination.parent.mkdir(parents=True, exist_ok=True)
350 with TemporaryDirectory(prefix=".qdpy-mp4-", dir=destination.parent) as directory:
351 root = Path(directory)
352 pending = root / "video.mp4"
353 common = _ffmpeg_inputs(executable, frames, root / "frames", fps)
354 _process([*common, "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2:color=white", "-c:v", "libx264",
355 "-pix_fmt", "yuv420p", "-threads", "1", "-movflags", "+faststart", str(pending)])
356 if not pending.is_file() or pending.stat().st_size == 0:
357 raise RuntimeError("FFmpeg did not write an MP4 video.")
358 if overwrite:
359 replace_file(pending, destination)
360 else:
361 destination.hardlink_to(pending)
362 return Path(output)
363
364
365
366def animate_archives(source, output, *, frames_dir=None, fps=8, encoder="auto", overwrite=False, **options):
367 """Write a GIF or ``.mp4`` video and optionally retain its PNG frames.
368
369 Forward rendering options, including trusted_pickle, to
370 ``render_archive_frames()``.
371 """
372 output = Path(output)
373 if output.exists() and not overwrite:
374 raise FileExistsError(output)
375 mp4 = output.suffix.lower() == ".mp4"
376 if mp4 and encoder not in ("auto", "ffmpeg"):
377 raise ValueError("MP4 output uses the FFmpeg encoder.")
378 encoding = {"fps": fps, "overwrite": overwrite}
379 assemble = assemble_mp4 if mp4 else assemble_gif
380 if not mp4:
381 encoding["encoder"] = encoder
382 if frames_dir is not None:
383 paths = render_archive_frames(source, frames_dir, **options)
384 return assemble(paths, output, **encoding)
385 output.parent.mkdir(parents=True, exist_ok=True)
386 with TemporaryDirectory(prefix=".qdpy-frames-", dir=output.parent) as directory:
387 paths = render_archive_frames(source, directory, **options)
388 return assemble(paths, output, **encoding)