Source code for qdpy._archive_animation

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Render archive histories and assemble ordered PNG frames into GIFs or MP4.

"""Render comparable archive frames and encode GIF or MP4 animations."""

from dataclasses import replace
from math import ceil, fsum, isfinite, prod, sqrt
from os import PathLike, replace as replace_file
from pathlib import Path
import re
import shutil
import subprocess
from tempfile import TemporaryDirectory
import warnings

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

from ._archive_comparison import _cell_bests, _cell_geometry
from ._archive_data import _named_data
from ._archive_history import _history_inputs, read_archive_history
from ._archive_plot import _colour_limits, _finite_extent, _plot_panels, _prepare_panel
from .base import _atomic_output_path

__all__ = ["render_archive_frames", "assemble_gif", "assemble_mp4", "animate_archives"]


def _panel_settings(name, defaults, panel_options):
    return defaults | panel_options.get(name, {})


def _union(left, right):
    if not left or not right:
        return left or right
    return min(left[0], right[0]), max(left[1], right[1])


def _scan_history(inputs, trusted_pickle, defaults, panel_options, shared_scale, show_progress):
    # Keep one layout template per archive and only extrema for later frames.
    templates = {}
    extents = {}
    values = {}
    empty = {}
    trends = {}
    last_budget = 0
    for frame in read_archive_history(inputs, trusted_pickle=trusted_pickle):
        if show_progress:
            if frame.evaluations is None or frame.evaluations < last_budget:
                raise ValueError("Progress curves need nondecreasing evaluation counts on every frame.")
            last_budget = frame.evaluations
        for name, archive in _named_data(frame.archives).items():
            if show_progress:
                objective = _panel_settings(name, defaults, panel_options).get("objective", 0)
                trends.setdefault(name, []).append((frame.evaluations, *_progress_metrics(archive, objective)))
            templates.setdefault(name, None)
            if not archive.dimension:
                empty.setdefault(name, archive)
                continue
            panel = _prepare_panel(archive, **_panel_settings(name, defaults, panel_options))
            if templates[name] is None:
                templates[name] = panel
                extents[name] = panel.limits
            elif templates[name].dimensions != panel.dimensions:
                raise ValueError(f"Descriptor axes changed for panel {name!r}. Set dimensions explicitly.")
            else:
                extents[name] = tuple(_union(a, b) for a, b in zip(extents[name], panel.limits))
            colour_range = _union(panel.hint, _finite_extent(panel.values))
            values[name] = _union(values.get(name, ()), colour_range)
    if set(panel_options) - set(templates):
        raise ValueError("Panel options must use an archive label.")
    for name, template in templates.items():
        if template is None:
            template = _prepare_panel(empty[name], **_panel_settings(name, defaults, panel_options))
            templates[name] = template
            extents[name] = template.limits
            values[name] = template.hint
    bounds = {name: replace(template, hint=values[name], values=np.empty(0))
              for name, template in templates.items()}
    shared = _colour_limits(list(bounds.values())) if shared_scale else None
    scales = {name: shared or _colour_limits([panel]) for name, panel in bounds.items()}
    return templates, scales, extents, trends


def _progress_metrics(archive, objective):
    """Sum the selected objective's normalized cell bests and count occupied cells."""
    occupied = {entry.cell for entry in archive.entries if entry.cell is not None}
    coverage = len(occupied) / prod(archive.shape) if archive.shape else np.nan
    if not 0 <= objective < len(archive.fitness_domain):
        return np.nan, coverage
    if not archive.entries:
        return 0., coverage
    low, high = archive.fitness_domain[objective]
    if not isfinite(low) or not isfinite(high):
        return np.nan, coverage
    if archive.shape:
        values = _cell_bests(archive, objective).values()
    else:
        values = ((entry.fitness[objective], entry.fitness_weights[objective]) for entry in archive.entries)
    score = fsum((high - raw if weight < 0 else raw - low) / (high - low or 1.)
                 for raw, weight in values if isfinite(raw))
    return score, coverage


def _draw_progress(fig, trends, evaluations, bottom):
    for coordinate, title, metric in ((.10, "Normalized QD score", 1), (.55, "Coverage", 2)):
        ax = fig.add_axes((coordinate, .075, .35, bottom - .163))
        for label, points in trends.items():
            ax.step([row[0] for row in points], [row[metric] for row in points], where="post",
                    label=label, linewidth=1.4)
        ax.axvline(evaluations, color="#394759", linestyle="--", linewidth=1)
        ax.set_title(title, fontsize=10)
        ax.set_xlabel("Evaluations")
        ax.grid(alpha=.22)
        if metric == 1 and len(trends) > 1:
            ax.legend(loc="best", fontsize=7, frameon=False)


def _highlight_cells(ax, panel, previous, objective):
    data = panel.archive
    if (previous is None or panel.view not in ("grid", "cvt") or panel.section
            or _cell_geometry(data) != _cell_geometry(previous)):
        return
    old, new = _cell_bests(previous, objective), _cell_bests(data, objective)
    filled, improved = [], []
    edges = data.bin_edges
    if not data.centroids and not edges:
        edges = tuple(np.linspace(*bounds, bins + 1) for bounds, bins in zip(data.descriptor_domain, data.shape))
    for cell, (raw, direction) in new.items():
        if cell in old and (old[cell][1] != direction or (raw - old[cell][0]) * direction <= 0):
            continue
        if data.centroids:
            position = [data.centroids[cell[0]][axis] for axis in panel.dimensions]
        else:
            position = [(edges[axis][cell[axis]] + edges[axis][cell[axis] + 1]) / 2 for axis in panel.dimensions]
        if len(position) == 1:
            position.append(.5)
        (improved if cell in old else filled).append(position)
    for points, marker, label in ((filled, "o", "New cell"), (improved, "^", "Improved")):
        if points:
            ax.scatter(*zip(*points), marker=marker, s=42, facecolors="#ffffff", edgecolors="#172638",
                       linewidth=.8, label=label, zorder=4)
    if filled or improved:
        ax.legend(loc="upper right", fontsize=7, framealpha=.9)


def _title(frame):
    detail = []
    if frame.iteration is not None:
        detail.append(f"Iteration {frame.iteration}")
    if frame.evaluations is not None:
        detail.append(f"{frame.evaluations:,} evaluations")
    return " · ".join(detail) or f"Frame {frame.number}"


## @brief Render archive history as fixed-size PNG frames with stable scales.
[docs] def render_archive_frames(source, output_dir, *, trusted_pickle=False, panel_options=None, shared_scale=False, columns=None, colorbar=True, figsize=None, dpi=100, show_progress=False, highlight_changes=False, **options): """Write numbered PNG frames and return their paths in time order. Use a history directory or the same input accepted by ``read_archive_history()``. View options follow ``plot_archives()``. Axis and colour limits are gathered across the history before drawing. The output directory must be new or empty. :param show_progress: Add QD score and coverage curves with a budget cursor. :param highlight_changes: Mark new and improved cells on stable planar geometry. """ if not isfinite(dpi) or dpi <= 0: raise ValueError("dpi must be positive and finite.") inputs = _history_inputs(source) panel_options = panel_options or {} templates, scales, limits, trends = _scan_history( inputs, trusted_pickle, options, panel_options, shared_scale, show_progress, ) bottom = None if show_progress: columns = min(len(templates), ceil(sqrt(len(templates)))) if columns is None else columns if columns < 1: raise ValueError("columns must be positive.") figsize = figsize or (max(7., 4.3 * columns), 3.7 * ceil(len(templates) / columns) + 2.2) bottom = max(.21, min(.48, 2.1 / figsize[1])) directory = Path(output_dir) directory.mkdir(parents=True, exist_ok=True) if any(directory.iterdir()): raise FileExistsError(f"Frame output directory must be empty: {directory}") paths = [] previous = {} for number, frame in enumerate(read_archive_history(inputs, trusted_pickle=trusted_pickle)): panels = {} for name, archive in _named_data(frame.archives).items(): settings = _panel_settings(name, options, panel_options) settings["dimensions"] = templates[name].dimensions panels[name] = _prepare_panel(archive, **settings) fig, axes = _plot_panels(panels, columns=columns, shared_scale=shared_scale, colorbar=colorbar, figsize=figsize, templates=templates, scales=scales, limits=limits, bottom=bottom) path = directory / f"frame-{number:06d}.png" try: fig.suptitle(_title(frame)) if show_progress: _draw_progress(fig, trends, frame.evaluations, bottom) if highlight_changes: for name, panel in panels.items(): objective = _panel_settings(name, options, panel_options).get("objective", 0) _highlight_cells(axes[name], panel, previous.get(name), objective) previous = {name: panel.archive for name, panel in panels.items()} with _atomic_output_path(path) as temporary, mpl.rc_context({"savefig.bbox": None}): fig.savefig(temporary, format="png", dpi=dpi) finally: plt.close(fig) paths.append(path) return tuple(paths)
def _natural_key(path): return [int(token) if i % 2 else token.casefold() for i, token in enumerate(re.split(r"(\d+)", path.name))], path.name def _png_inputs(frames): if isinstance(frames, (str, PathLike)): path = Path(frames) files = sorted((p for p in path.iterdir() if p.is_file() and p.suffix.lower() == ".png"), key=_natural_key) if path.is_dir() else [path] else: files = list(map(Path, frames)) if not files: raise ValueError("Provide at least one PNG frame.") size = None for path in files: with Image.open(path) as image: if image.format != "PNG": raise ValueError(f"Expected a PNG frame: {path}") if size is not None and image.size != size: raise ValueError("PNG frames must have identical pixel dimensions.") size = image.size image.verify() return [path.resolve() for path in files] def _process(args): proc = subprocess.run(args, check=False, capture_output=True, text=True, errors="replace") if proc.returncode: reason = proc.stderr.strip() or proc.stdout.strip() or f"exit status {proc.returncode}" raise RuntimeError(reason) def _ffmpeg_inputs(executable, frames, folder, fps): """Stage a contiguous image sequence for explicit or nonstandard frame names.""" folder.mkdir() for number, frame in enumerate(frames): shutil.copyfile(frame, folder / f"frame-{number:06d}.png") return [executable, "-hide_banner", "-loglevel", "error", "-y", "-filter_threads", "1", "-filter_complex_threads", "1", "-framerate", str(fps), "-start_number", "0", "-i", str(folder / "frame-%06d.png")] def _encode(name, executable, frames, output, fps): if name == "gifski": _process([executable, "--no-sort", "--fps", str(fps), "--repeat", "0", "--output", str(output), *map(str, frames)]) elif name == "ffmpeg": staged = output.parent / "ffmpeg" palette = staged / "palette.png" common = _ffmpeg_inputs(executable, frames, staged, fps) _process([*common, "-vf", "palettegen", "-frames:v", "1", str(palette)]) _process([*common, "-i", str(palette), "-lavfi", "paletteuse", "-loop", "0", str(output)]) else: images = [] for path in frames: with Image.open(path) as image: images.append(image.convert("RGBA")) # GIF stores centiseconds. Round cumulative frame timings to avoid drift. durations = [10 * (round((n + 1) * 100 / fps) - round(n * 100 / fps)) for n in range(len(images))] images[0].save(output, format="GIF", save_all=True, append_images=images[1:], duration=durations, loop=0) def _encoders(encoder): order = ("gifski", "ffmpeg", "pillow") if encoder != "auto" and encoder not in order: raise ValueError("Choose encoder='auto', 'gifski', 'ffmpeg', or 'pillow'.") for name in order if encoder == "auto" else (encoder,): executable = shutil.which(name) if name != "pillow" else None if name == "pillow" or executable: yield name, executable elif encoder != "auto": raise RuntimeError(f"{name} is unavailable on PATH.") ## @brief Assemble PNGs using gifski, FFmpeg, or Pillow.
[docs] def assemble_gif(frames, output, *, fps=8, encoder="auto", overwrite=False): """Encode looping GIF output and return its path. Directories use natural filename order. Explicit sequences keep the caller's order. Auto mode tries gifski, FFmpeg, and Pillow in sequence. Explicit encoder failures report the original diagnostic. """ destination = Path(output).absolute() if not isfinite(fps) or not 0 < fps <= 100: raise ValueError("fps must be in (0, 100] to fit GIF's centisecond timing.") if destination.exists() and not overwrite: raise FileExistsError(destination) frames = _png_inputs(frames) destination.parent.mkdir(parents=True, exist_ok=True) failures = [] with TemporaryDirectory(prefix=".qdpy-gif-", dir=destination.parent) as directory: for name, executable in _encoders(encoder): pending = Path(directory) / f"{name}.gif" try: _encode(name, executable, frames, pending, fps) with Image.open(pending) as image: if image.format != "GIF" or not image.n_frames: raise RuntimeError("Encoder did not write a readable GIF.") except (OSError, RuntimeError, ValueError) as error: detail = f"{name} failed: {error}" if encoder != "auto": raise RuntimeError(detail) from error failures.append(detail) warnings.warn(detail, RuntimeWarning, stacklevel=2) continue if overwrite: replace_file(pending, destination) else: # Atomically publish without overwriting a concurrently created file. destination.hardlink_to(pending) return Path(output) raise RuntimeError("Unable to encode GIF. " + "\n".join(failures))
## @brief Assemble ordered PNGs into a browser-compatible H.264 MP4.
[docs] def assemble_mp4(frames, output, *, fps=8, overwrite=False): """Encode a silent MP4 with the system FFmpeg and return the output path. Directories use natural filename order and explicit sequences retain caller order. Frames with odd dimensions are padded to even dimensions. """ destination = Path(output).absolute() if not isfinite(fps) or fps <= 0: raise ValueError("fps must be positive and finite.") if destination.exists() and not overwrite: raise FileExistsError(destination) executable = shutil.which("ffmpeg") if executable is None: raise RuntimeError("MP4 export requires ffmpeg on PATH.") frames = _png_inputs(frames) destination.parent.mkdir(parents=True, exist_ok=True) with TemporaryDirectory(prefix=".qdpy-mp4-", dir=destination.parent) as directory: root = Path(directory) pending = root / "video.mp4" common = _ffmpeg_inputs(executable, frames, root / "frames", fps) _process([*common, "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2:color=white", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-threads", "1", "-movflags", "+faststart", str(pending)]) if not pending.is_file() or pending.stat().st_size == 0: raise RuntimeError("FFmpeg did not write an MP4 video.") if overwrite: replace_file(pending, destination) else: destination.hardlink_to(pending) return Path(output)
## @brief Render archive history and assemble it into a GIF or MP4.
[docs] def animate_archives(source, output, *, frames_dir=None, fps=8, encoder="auto", overwrite=False, **options): """Write a GIF or ``.mp4`` video and optionally retain its PNG frames. Forward rendering options, including trusted_pickle, to ``render_archive_frames()``. """ output = Path(output) if output.exists() and not overwrite: raise FileExistsError(output) mp4 = output.suffix.lower() == ".mp4" if mp4 and encoder not in ("auto", "ffmpeg"): raise ValueError("MP4 output uses the FFmpeg encoder.") encoding = {"fps": fps, "overwrite": overwrite} assemble = assemble_mp4 if mp4 else assemble_gif if not mp4: encoding["encoder"] = encoder if frames_dir is not None: paths = render_archive_frames(source, frames_dir, **options) return assemble(paths, output, **encoding) output.parent.mkdir(parents=True, exist_ok=True) with TemporaryDirectory(prefix=".qdpy-frames-", dir=output.parent) as directory: paths = render_archive_frames(source, directory, **options) return assemble(paths, output, **encoding)