Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/maxplotlib/tests/test_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,25 @@ def test_a_figure_without_caption_has_none():
canvas.plot(np.arange(3), np.arange(3))
figure, _ = canvas.plot_matplotlib()
assert getattr(figure, "caption", None) is None


def test_the_arrays_of_a_web_figure_are_single_precision():
import base64

x = np.linspace(0.0, 1.0, 50)
fig = go.Figure(
go.Heatmap(z=np.outer(x, x)),
frames=[go.Frame(data=[go.Heatmap(z=np.outer(x, x) * 2)])],
)
web = web_figure(fig)
z = web["data"][0]["z"]
assert z["dtype"] == "f4"
values = np.frombuffer(base64.b64decode(z["bdata"]), dtype="<f4").reshape(50, 50)
np.testing.assert_allclose(values, np.outer(x, x), rtol=1e-7)
assert web["frames"][0]["data"][0]["z"]["dtype"] == "f4"
# plain lists and integer arrays are left as they are
web = web_figure(
go.Figure(go.Scatter(x=[0, 1], y=np.array([1, 2], dtype=np.int64)))
)
assert web["data"][0]["x"] == [0, 1]
assert web["data"][0]["y"]["dtype"] != "f4"
40 changes: 37 additions & 3 deletions src/maxplotlib/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

from __future__ import annotations

import base64
import json
import re
from pathlib import Path
Expand Down Expand Up @@ -169,6 +170,29 @@ def _title_text(layout: dict) -> str | None:
return title if isinstance(title, str) and title else None


def _single_precision(value: Any) -> Any:
"""``value`` with its double-precision arrays in single precision.

Plotly writes NumPy arrays as typed arrays, ``{"dtype": "f8", "bdata": ...}``; a figure on a
page needs no more than the seven digits of single precision, and its file is half as large.
"""
if isinstance(value, dict):
if value.get("dtype") == "f8" and isinstance(value.get("bdata"), str):
import numpy as np

data = np.frombuffer(base64.b64decode(value["bdata"]), dtype="<f8")
single = data.astype("<f4")
return {
**value,
"dtype": "f4",
"bdata": base64.b64encode(single.tobytes()).decode(),
}
return {key: _single_precision(item) for key, item in value.items()}
if isinstance(value, list):
return [_single_precision(item) for item in value]
return value


def _with_slot(trace: dict) -> dict:
slot = _trace_slot(trace)
if slot is None:
Expand Down Expand Up @@ -207,7 +231,9 @@ def web_figure(
Returns
-------
dict
``data``, ``layout`` and ``frames`` (when the figure has frames) of the web figure.
``data``, ``layout`` and ``frames`` (when the figure has frames) of the web figure. The
arrays of the traces are in single precision: seven digits are plenty on a page, and
the file is half as large.

Examples
--------
Expand Down Expand Up @@ -251,13 +277,21 @@ def web_figure(
layout["meta"] = meta

web = {
"data": [_with_slot(trace) for trace in source.get("data") or []],
"data": [
_single_precision(_with_slot(trace)) for trace in source.get("data") or []
],
"layout": layout,
}
frames = source.get("frames")
if frames:
web["frames"] = [
{**frame, "data": [_with_slot(trace) for trace in frame.get("data") or []]}
{
**frame,
"data": [
_single_precision(_with_slot(trace))
for trace in frame.get("data") or []
],
}
for frame in frames
]
return web
Expand Down
Loading