QDpy
Loading...
Searching...
No Matches
visualization.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Render QDpy results with `python -m qdpy.visualization`."""
6
7import argparse
8from pathlib import Path
9
10
11def _slice_coordinates(values):
12 if values is None:
13 return None
14 coordinates = {}
15 for item in values:
16 axis, value = item.split("=", 1)
17 key = int(axis)
18 if key in coordinates:
19 raise ValueError(f"Duplicate slice axis {key}.")
20 coordinates[key] = float(value)
21 return coordinates
22
23
24def _add_view_options(parser):
25 parser.add_argument("--trusted-pickle", action="store_true", help="Allow checkpoints from a trusted source")
26 parser.add_argument("--view", choices=("auto", "grid", "cvt", "scatter", "sphere"), default="auto")
27 parser.add_argument("--dimensions", nargs="+", type=int, help="Zero-based descriptor indices")
28 parser.add_argument("--slice-at", metavar="AXIS=VALUE", action="append", help="Fix an omitted axis")
29 parser.add_argument("--sphere-center", nargs=3, type=float, default=(0, 0, 0))
30 parser.add_argument("--metric", choices=("fitness", "occupancy", "activity"), default="fitness")
31 parser.add_argument("--objective", type=int, default=0)
32 parser.add_argument("--shared-scale", action="store_true")
33 parser.add_argument("--vmin", type=float)
34 parser.add_argument("--vmax", type=float)
35 parser.add_argument("--columns", type=int)
36 parser.add_argument("--dpi", type=float, default=100)
37
38
39def _png_source(path):
40 if not path.is_dir():
41 return path.suffix.lower() == ".png"
42 from ._archive_history import _history_inputs
43
44 return not _history_inputs(path) and any(p.is_file() and p.suffix.lower() == ".png" for p in path.iterdir())
45
46
47def _plot(source, output, overwrite, dpi, trusted_pickle, options):
48 import matplotlib.pyplot as plt
49
50 from .base import _atomic_output_path
51 from .plots import plot_archives, read_archive_history
52
53 if output.exists() and not overwrite:
54 raise FileExistsError(output)
55 frame = None
56 for frame in read_archive_history(source, trusted_pickle=trusted_pickle):
57 pass
58 fig, _ = plot_archives(frame.archives, **options)
59 style = output.suffix.lower().lstrip(".") or "png"
60 try:
61 output.parent.mkdir(parents=True, exist_ok=True)
62 with _atomic_output_path(output) as temporary:
63 fig.savefig(temporary, format=style, dpi=dpi)
64 finally:
65 plt.close(fig)
66
67
68
69def main(argv=None):
70 """Run the plotting, frame rendering, or animation command."""
71 parser = argparse.ArgumentParser(description=__doc__)
72 subcommands = parser.add_subparsers(dest="command", required=True)
73 for name, summary in (("plot", "Plot the last archive frame"), ("frames", "Render a history to PNGs"),
74 ("gif", "Animate a history or PNGs as a GIF"),
75 ("mp4", "Animate a history or PNGs as an MP4")):
76 command = subcommands.add_parser(name, help=summary)
77 command.add_argument("source", type=Path)
78 command.add_argument("-o", "--output", type=Path, required=True)
79 if name != "frames":
80 command.add_argument("--overwrite", action="store_true")
81 if name in ("gif", "mp4"):
82 command.add_argument("--fps", type=float, default=8)
83 command.add_argument("--frames-dir", type=Path, help="Keep the rendered PNGs here")
84 if name == "gif":
85 command.add_argument("--encoder", choices=("auto", "gifski", "ffmpeg", "pillow"), default="auto")
86 if name != "plot":
87 command.add_argument("--show-progress", action="store_true")
88 command.add_argument("--highlight-changes", action="store_true")
89 _add_view_options(command)
90 args = parser.parse_args(argv)
91
92 import matplotlib
93
94 matplotlib.use("Agg")
95 from .plots import animate_archives, assemble_gif, assemble_mp4, render_archive_frames
96
97 try:
98 options = dict(view=args.view, dimensions=args.dimensions, slice_at=_slice_coordinates(args.slice_at),
99 sphere_center=tuple(args.sphere_center), metric=args.metric, objective=args.objective,
100 shared_scale=args.shared_scale, vmin=args.vmin, vmax=args.vmax, columns=args.columns)
101 save = dict(dpi=args.dpi, trusted_pickle=args.trusted_pickle, **options)
102 if args.command != "plot":
103 save.update(show_progress=args.show_progress, highlight_changes=args.highlight_changes)
104 if args.command == "plot":
105 _plot(args.source, args.output, args.overwrite, args.dpi, args.trusted_pickle, options)
106 elif args.command == "frames":
107 render_archive_frames(args.source, args.output, **save)
108 else:
109 mp4 = args.command == "mp4"
110 if mp4 != (args.output.suffix.lower() == ".mp4"):
111 raise ValueError("Use the mp4 subcommand and a .mp4 output path together.")
112 encoding = dict(fps=args.fps, overwrite=args.overwrite)
113 if _png_source(args.source):
114 if mp4:
115 assemble_mp4(args.source, args.output, **encoding)
116 else:
117 assemble_gif(args.source, args.output, encoder=args.encoder, **encoding)
118 else:
119 animate_archives(args.source, args.output, frames_dir=args.frames_dir,
120 encoder=getattr(args, "encoder", "ffmpeg"), **encoding, **save)
121 except (OSError, ValueError, RuntimeError, KeyError, TypeError) as error:
122 parser.exit(2, f"{parser.prog}: {error}\n")
123 print(args.output)
124
125
126if __name__ == "__main__":
127 main()