Skip to content
15 changes: 15 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,25 @@ Network plots and animations
``n_jobs``, which draws frames in worker processes. With ``n_jobs`` other
than 1, a blank (black) render or a dead worker restarts the pool, up to 5
times.
- :func:`htfa.plot_network` accepts ``caption``, one line of text drawn as
:func:`htfa.animate_network` draws a frame's caption: in a band above the
image, or, with ``views``, ``legend`` or ``frame_size``, on a line under the
view titles. The caption is drawn by the same code as a movie's. The image
equals the frame of a one-window movie with ``captions=[caption]`` when
both crop the views to the same box (a still is cropped around its nodes as
drawn, a movie around opaque nodes in one contrasting color).
- An empty legend row reserves a blank band of the normal row height:
``legend=[[], row]`` puts the row one band lower, and a legend of empty rows
only is allowed. ``legend=[]`` still raises ``ValueError``.
- ``crf`` and ``faststart`` set the x264 constant rate factor and move the mp4
index to the start of the file, in :func:`htfa.animate_network` and
:func:`htfa.brainnet.write_animation`. With ``crf=None`` the encoding is as
in 0.1.0.
- ``preset`` passes an x264 preset name (``"ultrafast"`` to ``"placebo"``) to
the encoder, in :func:`htfa.animate_network` and
:func:`htfa.brainnet.write_animation`. Other names raise ``ValueError``, and
so does a GIF output, as for ``crf``. With ``preset=None`` the encoding is
as in 0.1.0.
- The style key ``supersample`` sets the rendering multiple used for
anti-aliasing (default 2).
- :func:`htfa.content_box` returns the bounding box of the non-background
Expand Down
37 changes: 32 additions & 5 deletions docs/superpowers/specs/2026-11-21-network-plots-188-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ movies through htfa's public functions alone.
3. Several views composed in one frame.
4. A legend of colored dots and lines with labels.
5. Frames rendered in parallel workers.
6. Encoding options (`crf`, `faststart`) for MP4 output.
6. Encoding options (`crf`, `faststart`, `preset`) for MP4 output.
7. A public `content_box` crop helper.
8. A `compose=` callable on `animate_network` for callers who want their own
frame layout.
Expand All @@ -32,8 +32,6 @@ movies through htfa's public functions alone.
- Editing the timecorr repository. Its session does that once 0.2.0 exists.
- Node positions that change over time.
- A public scene class. `_Scene` stays private.
- An x264 `preset` option (the tutorial uses `slow`; the issue does not ask
for it).

## Anti-goals

Expand Down Expand Up @@ -168,6 +166,13 @@ black text, mark then
label, sizes proportional to the font size (gap 40, mark width 34, dot
radius 12, line width 6, mark-to-text 10, all per 30 px of font).

Empty rows (added 2026-11-22): in a list of rows, an empty row reserves one
band in the background color at its position, so `[[], row]` draws the row
one band lower and `[row, []]` leaves a blank band under it; a legend of
empty rows only is allowed. Without `frame_size` the frame is one band
taller per empty row; with it, the views get one band less height.
`legend=[]` still raises `ValueError`.

### `compose`

New keyword `compose` on `animate_network`: a callable
Expand All @@ -181,6 +186,20 @@ With `n_jobs` other than 1 the callable runs in worker processes.
`plot_network` has no `compose`: a caller can render each view and combine
the images directly.

### `caption` on `plot_network`

Added 2026-11-22, after a downstream port of the animation tutorial.
`plot_network(..., caption=None)` takes one line of text and finishes its
image with the same helper that finishes each `animate_network` frame, so
the caption is drawn as in a movie: in the 0.1.0 path, a `_with_header`
band above the image; in the layout path, a line under the view titles
(with `frame_size`, the views get that much less height). The crops are not
unified: a still is cropped around its nodes as drawn, a movie around
opaque nodes in one contrasting color at their largest radius. Where the
two boxes are equal (always in the 0.1.0 path), the image equals the frame
of a one-window movie with `captions=[caption]`. `None` changes nothing. A caption that is not a str
raises `ValueError`.

### Parallel rendering

New keyword `n_jobs=1` on `animate_network`. With 1, frames are drawn in
Expand Down Expand Up @@ -219,14 +238,22 @@ callers can trade quality for speed without touching a private global.

### Encoding

`write_animation(images, out, fps=10, *, crf=None, faststart=False)`.
`write_animation(images, out, fps=10, *, crf=None, faststart=False,
preset=None)`.

- `crf`: integer 0 to 51. When given, imageio's `quality` is set to `None`
and `-crf` is passed to ffmpeg. When `None`, encoding is as in 0.1.0.
- `faststart`: adds `-movflags +faststart`.
- Either option with a GIF output raises `ValueError`.

`animate_network` gains the same two keywords and forwards them.
- `preset` (added 2026-11-22): one of x264's presets (`ultrafast`,
`superfast`, `veryfast`, `faster`, `fast`, `medium`, `slow`, `slower`,
`veryslow`, `placebo`), passed as `-preset`; any other value raises
`ValueError` naming it and the allowed names. It works with or without
`crf` and `faststart`; with a GIF output it raises `ValueError`, as `crf`
does. `None` passes no `-preset`, so the encoding is as in 0.1.0.

`animate_network` gains the same three keywords and forwards them.

### `content_box`

Expand Down
175 changes: 90 additions & 85 deletions docs/tutorials/10_dynamic_isfc_animation.ipynb

Large diffs are not rendered by default.

352 changes: 205 additions & 147 deletions docs/tutorials/11_plotting_and_appearance.ipynb

Large diffs are not rendered by default.

108 changes: 89 additions & 19 deletions htfa/brainnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -1915,6 +1915,7 @@ def plot_network(
views: Sequence[Any] | None = None,
legend: Any = None,
frame_size: tuple[int, int] | None = None,
caption: str | None = None,
**style: Any,
) -> Any:
"""Render nodes and thresholded edges BrainNet Viewer-style.
Expand Down Expand Up @@ -2008,7 +2009,9 @@ def plot_network(
views (the title fonts follow the same W). Without ``frame_size`` the
image widens to hold the widest row (views centered), and the fonts
keep the size set by the views' width; with it, a wider row raises
``ValueError``.
``ValueError``. An empty row in a list of rows (``[[], row]``,
``[row, []]``, or empty rows only) reserves a blank band of the
same height in its place. ``[]`` raises ``ValueError``.
frame_size : (W, H) positive ints, optional
Exact size of the image: titles and legend are drawn at width W and
the views are scaled (Lanczos, up or down) to fit the space left,
Expand All @@ -2020,6 +2023,20 @@ def plot_network(
layout path; the title and legend bands take the ``background``
color, with black text on a light background and white text on a
dark one. Without them the single ``view`` is returned uncropped.
caption : str, optional
One line of text, drawn as `animate_network` draws a frame's
caption: without ``views``, ``legend`` and ``frame_size``, in a
white band added above the image; with any of them, centered on a
line under the view titles, in the title band (with ``frame_size``
the views get that much less height). Text wider than the image is
cut off at its edges. ``None`` (default) adds nothing. The caption
is drawn by the same code as in `animate_network`. The crop of the
views can differ from a movie's: a still is cropped around its nodes
as drawn, a movie around opaque nodes in one contrasting color at
their largest radius. Where the two crop boxes are equal (always
without ``views``, ``legend`` and ``frame_size``, which do not
crop), the image equals the frame of a one-window movie with
``captions=[caption]`` and the same other arguments.
**style
``threshold`` (0.25; edges with ``|E| > threshold`` are drawn),
``view`` (``"lateral"`` = ``"left"``, ``"right"``, ``"dorsal"``,
Expand Down Expand Up @@ -2054,8 +2071,8 @@ def plot_network(
or ``frame_size`` is malformed, a legend row is wider than
``frame_size``, ``sizes`` does not hold exactly K values (K values
in any shape, such as (1, K) or (K, 1), are accepted; (T, K) sizes
are for `animate_network`), or ``node_color`` has a shape other than
one color or K colors.
are for `animate_network`), ``node_color`` has a shape other than
one color or K colors, or ``caption`` is not a str.

Examples
--------
Expand All @@ -2067,6 +2084,8 @@ def plot_network(
... legend=[("red", "positive", "line"), ("blue", "negative", "line")],
... frame_size=(1920, 1080)) # doctest: +SKIP
"""
if caption is not None and not isinstance(caption, str):
raise ValueError(f"caption must be a str or None, got {caption!r}")
layout = _layout_args(views, legend, frame_size, style)
scene_opts, edge_opts = _style(dict(style))
centers, node_sizes, opacity, components, surfaces = _network_geometry(
Expand Down Expand Up @@ -2116,13 +2135,10 @@ def plot_network(
images = scenes.draw(E, edge_opts)
finally:
scenes.close()
if layout is None:
img = images[0]
else:
_, titles, rows, size = layout
img = _layout(
images, titles, None, rows, crop, None, size, scene_opts["background"]
)
# titles, caption and legend as animate_network finishes a frame
img = _finish_frame(
images, 0.0, caption, layout, crop, scene_opts["background"], None
)
if jpeg_quality is not None:
img = _jpeg(img, jpeg_quality)
if out is not None:
Expand Down Expand Up @@ -2228,6 +2244,7 @@ def animate_network(
n_jobs: int = 1,
crf: int | None = None,
faststart: bool = False,
preset: str | None = None,
**style: Any,
) -> Path:
"""Render a ``(T, K, K)`` connectivity series as an mp4 or GIF.
Expand All @@ -2237,9 +2254,9 @@ def animate_network(
``n_frames``) sets the number of frames instead, interpolating between
windows, and ``spin`` turns the brain. A call that gives none of
``views``, ``legend``, ``frame_size``, ``compose``, ``n_jobs``, ``crf``,
``faststart``, (T, K) ``sizes`` or colors, or ``None`` connectivity is
drawn and encoded as in 0.1.0. ``views``, ``legend`` or ``frame_size``
take the layout path described under `plot_network`.
``faststart``, ``preset``, (T, K) ``sizes`` or colors, or ``None``
connectivity is drawn and encoded as in 0.1.0. ``views``, ``legend`` or
``frame_size`` take the layout path described under `plot_network`.

Parameters
----------
Expand Down Expand Up @@ -2375,6 +2392,11 @@ def animate_network(
faststart : bool, default False
Move the mp4 index to the start of the file, so that browsers can
play it while it downloads; passed to `write_animation`.
preset : str, optional
x264 preset of an mp4 (``"ultrafast"`` to ``"placebo"``; slower
presets usually compress better at the same ``crf``); passed to
`write_animation`. Default ``None``: x264's default (medium), as in
0.1.0.

Returns
-------
Expand Down Expand Up @@ -2560,7 +2582,9 @@ def frames() -> Iterator[Any]:
img = _draw_frame(scenes, movie, k)
yield _frame_out(img, k, jpeg_quality, folder)

return write_animation(frames(), out, fps=fps, crf=crf, faststart=faststart)
return write_animation(
frames(), out, fps=fps, crf=crf, faststart=faststart, preset=preset
)
# select the offscreen window here (Linux without a display), so that the
# workers inherit the choice instead of each probing for it
_headless_window()
Expand All @@ -2572,7 +2596,9 @@ def drawn() -> Iterator[Any]:
for k in range(len(times)):
yield _frame_out(_open(work / f"{k:05d}.png"), k, jpeg_quality, folder)

result = write_animation(drawn(), out, fps=fps, crf=crf, faststart=faststart)
result = write_animation(
drawn(), out, fps=fps, crf=crf, faststart=faststart, preset=preset
)
except BaseException as err:
_remove_work(work, err)
raise
Expand Down Expand Up @@ -2799,13 +2825,28 @@ def _draw_parallel(build: _ViewsArgs, movie: _Movie, n_jobs: int, work: Path) ->
# ------------------------------------------------------------------ animations


_X264_PRESETS = (
"ultrafast",
"superfast",
"veryfast",
"faster",
"fast",
"medium",
"slow",
"slower",
"veryslow",
"placebo",
)


def write_animation(
images: Iterable[Any],
out: str | os.PathLike,
fps: float = 10,
*,
crf: int | None = None,
faststart: bool = False,
preset: str | None = None,
) -> Path:
"""Write PIL images as an mp4 (H.264, yuv420p) or looping GIF, by suffix.

Expand Down Expand Up @@ -2836,6 +2877,14 @@ def write_animation(
faststart : bool, default False
Move the mp4 index to the start of the file so that browsers can
play it while it downloads. Not for GIF (``ValueError``).
preset : str, optional
x264 ``-preset``, one of ``"ultrafast"``, ``"superfast"``,
``"veryfast"``, ``"faster"``, ``"fast"``, ``"medium"``, ``"slow"``,
``"slower"``, ``"veryslow"`` and ``"placebo"``: slower presets take
longer and usually give a smaller file at the same ``crf``. Works
with or without ``crf`` and ``faststart``. Default ``None``: no
``-preset`` is passed (x264's default, medium), as in 0.1.0. Another
value raises ``ValueError``; not for GIF (``ValueError``).
"""
_check_fps(fps)
out = Path(out)
Expand All @@ -2848,6 +2897,18 @@ def write_animation(
or not 0 <= crf <= 51
):
raise ValueError(f"crf must be an integer from 0 to 51, got {crf!r}")
if preset is not None and (
not isinstance(preset, str) or preset not in _X264_PRESETS
):
raise ValueError(
f"preset must be None or one of x264's presets "
f"{', '.join(_X264_PRESETS)}; got {preset!r}"
)
if suffix == ".gif" and preset is not None:
raise ValueError(
f"crf, faststart and preset apply to .mp4 only, got {out.name!r} "
f"with crf={crf!r}, faststart={faststart!r}, preset={preset!r}"
)
if suffix == ".gif" and (crf is not None or faststart):
raise ValueError(
f"crf and faststart apply to .mp4 only, got {out.name!r} "
Expand All @@ -2867,6 +2928,12 @@ def write_animation(
options: dict[str, Any] = {"quality": 8}
if crf is not None:
options = {"quality": None, "output_params": ["-crf", str(int(crf))]}
if preset is not None:
options["output_params"] = [
*options.get("output_params", []),
"-preset",
preset,
]
if faststart:
options["output_params"] = [
*options.get("output_params", []),
Expand Down Expand Up @@ -3124,7 +3191,8 @@ def _legend_rows(legend: Any) -> list[list[tuple[tuple[int, int, int], str, str]
"""Legend rows of ``(rgb, label, kind)``, ``rgb`` as 0-255 ints.

``legend`` is one row, a list of ``(color, label, kind)`` with ``kind``
``"dot"`` or ``"line"``, or a list of such rows.
``"dot"`` or ``"line"``, or a list of such rows. An empty row (in a list
of rows) is kept: it reserves a blank band.
"""

def seq(x: Any) -> bool:
Expand All @@ -3138,8 +3206,6 @@ def seq(x: Any) -> bool:
nested = all(seq(row) and all(seq(e) for e in row) for row in legend)
rows = []
for r, row in enumerate(legend if nested else [legend], 1):
if not row:
raise ValueError(f"legend row {r} is empty")
entries = []
for entry in row:
if not (
Expand Down Expand Up @@ -3322,6 +3388,10 @@ def ink(v: int) -> tuple[int, int, int]:
x = x0 + k * pw
d.line([(x, y0), (x, y0 + ph)], fill=ink(200), width=2)
if rows:
for r, row in enumerate(rows):
if not row: # a reserved band is blank, also where a divider ends
y = H - legend_h + r * band
d.rectangle([0, y, W - 1, y + band - 1], fill=bg)
_draw_legend(d, rows, W, H - legend_h, band, lsize, ink(0))
if not frame_size and not width:
canvas = canvas.crop((0, 0, W - W % 2, H - H % 2))
Expand All @@ -3343,7 +3413,7 @@ def _legend_row_widths(rows: list, size: int) -> list[float]:
font, gap, mark, _, _, pad = _legend_geometry(size)
return [
sum(mark + pad + font.getlength(label) for _, label, _ in row)
+ gap * (len(row) - 1)
+ gap * max(len(row) - 1, 0)
for row in rows
]

Expand Down
4 changes: 2 additions & 2 deletions htfa/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,7 +1127,7 @@ def plot_network(
Other keyword arguments go to `htfa.brainnet.plot_network`, among
them ``node_color`` (one color, or one per factor), ``views``,
``legend`` and ``frame_size`` (several views and a legend in one
image). Needs the ``brain3d`` extra.
image) and ``caption`` (a line of text). Needs the ``brain3d`` extra.
"""
subject = self._target(subject, group)
if subject == "global" and self.global_centers is None:
Expand Down Expand Up @@ -1158,7 +1158,7 @@ def animate_network(
``duration`` (seconds; frames interpolated between windows, see
``interpolation``), ``spin`` (turns about x, y, z), ``node_color``,
``views``, ``legend``, ``frame_size``, ``compose``, ``n_jobs``,
``crf`` and ``faststart``. Needs the ``brain3d`` extra.
``crf``, ``faststart`` and ``preset``. Needs the ``brain3d`` extra.

Examples
--------
Expand Down
6 changes: 6 additions & 0 deletions notes/2026-11-21-issue-188-network-plots.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,9 @@
- NOT done, waits for the user's review and explicit go: PyPI/TestPyPI upload, publishing the draft release (creates the tag and a Zenodo archive), DOI badge. Procedure: release-preparation/README.md (trusted publishers and GitHub environments are not configured; publish.yml.example is inactive; its README still says version 0.1.0).
- Remaining tidy-up after the user's review: delete .superpowers/sdd/2026-11-21-network-plots-188/, decide whether to delete the merged branch.
- User asked that the README not name a specific version: release-preparation/README.md now points to pyproject.toml and docs/changelog.rst (README.md had no version number). Pushed straight to main at the user's choice; the draft release is re-pointed at that commit.

## 2026-11-23: Read the Docs fix and three additions before the release
- Read the Docs build of main times out (30 min). Cause: examples/plot_2d_image_factors.py, K=320 fit (from #186): its first Levenberg-Marquardt solve takes 84 s natively on this Mac and 500-1300 s on x86 depending on the OpenBLAS kernel. User chose: keep K=6 and K=80 in the gallery; tutorial 05 already shows K=320. PR #190 (branch fix/rtd-gallery-time, d03f53e): sphinx step 62 s vs 557 s in an RTD-like container. The slow solve itself is not fixed.
- timecorr ported its tutorial to the 0.2.0 API (main 56cb1a1) and reported three gaps; user chose to add all three to 0.2.0: plot_network(caption=), an empty legend row reserving a band, preset= for x264. Branch feature/network-plot-gaps; codex review: no major, four minor findings, all fixed; Ubuntu 26.04 container 183 passed.
- Still to do: merge both PRs after CI, re-point the draft release at the new main, confirm the Read the Docs build, then wait for the user's review before PyPI. Tell timecorr when 0.2.0 is on PyPI (it holds timecorr 0.3.1 for that).
- Untraced: "RuntimeWarning: invalid value encountered in <lambda> (vectorized)" after examples/plot_load_inputs.py in the Linux docs container only.
Loading
Loading