qewton.visualization.renderers package

Module contents

Renderers

A renderer draws one Figure in one plotting framework and one theme. Plots and figures stay framework-neutral; everything in a framework’s vocabulary (its figure, styling, embedded controls, export) lives here. See the visualization README.

Available renderers (__init__.py)

RENDERER_DICT holds the renderers whose packages are installed, in order of priority: "plotly" (PlotlyRenderer, if Plotly is installed), then "matplotlib" (MatplotlibRenderer, always: Matplotlib is a core dependency). DEFAULT_RENDERER, the renderer of a figure created without one, is the first of them. A new renderer is one more guarded import and entry; renderers are passed to a Figure as instances.

Interface (base.py)

  • Renderer(theme): bound to one figure by setup(figure), which builds the framework’s figure with the cell grid. The figure calls draw(key, result, cell, visible) per drawn copy (creating or updating the artist of key), hide(key), draw_axes(cell), draw_colorbar(scale, title, ticks, cell, slot, visible) (the cell it stands beside and its place there) and draw_legend(entries, cell) ({label: keys}). To embed a control it takes a snapshot(keys, cells, scales) per state and passes them to animate, apply_slider or apply_selector; the class attributes embeddable (kinds of control) and max_embedded (per output, None for no limit) declare what it embeds. Last, draw_layout() sizes the framework’s figure and places everything in it. Outputs: show (inline in a notebook at the figure’s size, notebook_html), save_html, save_image, save_gif.

  • Artist: draws one Result into one cell: create(backend_figure, result, cell, theme), update(...) in place, set_visible(...). An artist sees Results, cells and the theme, never plots. Renderer.artists maps (Result class, number of positions) to the artist class; a Result without one raises a ValueError naming the renderer.

  • text.py: texts of the core (plain parts and \(...\) math) as parts or as plain text, for every renderer.

  • space.py: the room beside the plot areas, for every renderer: tick labels and titles of the axes, cell titles, colorbars by cell and slot, legends, estimated from the number of characters and the font sizes.

Plotly (plotly/)

Module

Holds

__init__.py

PlotlyRenderer: cell grid, axes, colorbars (colorbar(scale)), legends, snapshots, outputs

layout.py

the figure size and the places of cells, titles, colorbars, legends and embedded controls in paper coordinates

embedding.py

embedded states as the trace and axis properties that differ between them

primitives.py

the artists of the primitive Results

graph.py, card_geometry.py

NodeLinkArtist for computation graphs and the geometry of its cards

traces.py

value bins, segment and triangle coordinates

text.py

texts with math as Plotly displays them

camera.py

the script moving the cameras of linked 3D cells together

PlotlyRenderer(theme=DEFAULT_THEME, mathjax=True): with MathJax, every text naming a Variable is written as one math text, and show() in a notebook displays HTML that loads plotly.js and MathJax from a CDN; mathjax=False writes Plotly’s own markup and needs no CDN. Axis titles of 3D scenes are markup in either case. The figure is sized in pixels without margins; embedded sliders stand below the cells, dropdowns right of them. Embedded controls become frames (time), slider steps and dropdown buttons that set only what differs between states; animations start with their play button and switch frames without transitions. Cells sharing position axes zoom together; linked 3D cells move their cameras together in HTML outputs and Dash.

from qewton.visualization import Figure
from qewton.visualization.renderers import PlotlyRenderer

backend_figure = Figure(plot, renderer=PlotlyRenderer(mathjax=False)).draw()

Matplotlib (matplotlib/)

Module

Holds

__init__.py

MatplotlibRenderer: cell grid, axes, colorbars, snapshots and frames, outputs

primitives.py

the artists of the primitive Results; axes_of(backend_figure, cell) and colorbar_axes(backend_figure, cell=None)

style.py

the theme as rcParams (fonts, sizes in points at PIXELS_PER_INCH, colors), colormaps and norms

text.py

texts with math as mathtext displays them, and plain characters cmr10 lacks as math

MatplotlibRenderer(theme=DEFAULT_THEME, usetex=False, dpi=100) draws a matplotlib.figure.Figure without pyplot; draw() returns it for further editing. Texts are mathtext in Computer Modern (text in the theme’s serif fonts, falling back to cmr10); math mathtext cannot parse is written as plain text, with a warning; usetex=True renders all text with LaTeX and needs latex.

Result

2D

3D

HeatmapResult

pcolormesh

–

SurfaceResult

tripcolor (Gouraud) or one fill, triplot edges

Poly3DCollection, shaded if uniform

LineResult

LineCollection

Line3DCollection

MarkerResult

scatter

scatter

BarResult

bar

–

ImageResult

pcolormesh of RGB(A) cells

–

ArrowResult

quiver

quiver

The figure is sized from the plot sizes and the room estimated beside them; constrained layout places everything when rendering, so a plot area may miss its size by a few pixels. A colorbar is an Axes inside its cell’s, right of the plot area and as tall.

Not drawn: ParallelCoordinatesResult and GraphLayoutResult. 2D cells sharing position axes share their Matplotlib axes; 3D cells are not linked. One TimeAxis or SliderAxis per output is embedded as frames: show() and save_html() give Matplotlib’s JavaScript player, save_gif() a GIF with the frame weights as durations; the figure title names the state of a frame. Images: PNG, SVG and PDF without external tools. show() displays HTML in a notebook and opens a window of Matplotlib’s backend elsewhere.

from qewton.visualization import Figure, WidgetApplication
from qewton.visualization.renderers import MatplotlibRenderer

figure = Figure(plot, renderer=MatplotlibRenderer())
figure.save_svg("figure.svg")
WidgetApplication.create(figure)  # in a notebook: a widget per control

See DECISIONS.md for design decisions.

qewton.visualization.renderers.RENDERER_DICT: dict[str, type[Renderer]] = {'matplotlib': <class 'qewton.visualization.renderers.matplotlib.MatplotlibRenderer'>}

The renderers whose packages are installed, in order of priority.

qewton.visualization.renderers.DEFAULT_RENDERER

Renderer class of a Figure created without a renderer: the first available one.

Subpackages

Submodules

qewton.visualization.renderers.base module

class qewton.visualization.renderers.base.Renderer(theme: Theme = Theme(background_color='#ffffff', text_color='#14181c', line_color='#14181c', grid_color='rgba(20,24,28,0.12)', font_family='Latin Modern Roman, CMU Serif, Georgia, serif', font_size_title=16, font_size_axes=14, font_size_labels=12, plot_width=400, plot_height=320, show_grid=False, show_zero_line=False, show_legend=True, legend_box=False, show_axis_line=True, axis_box=False, marker_size=6, line_width=1.25, opacity_default=0.8, surface_opacity=0.9, wireframe_opacity=0.3, geometry_color='#ebe2d9', vector_color='#14181c', primary_color_palette=['#f38f7f', '#fddb91', '#99bcdf', '#a18e7f', '#f9b381', '#8d89ba', '#94c9ad'], sequential_cmap=cmaps.meadow, diverging_cmap=cmaps.redblue, cyclic_cmap=cmaps.phase, node_color_by_type={'constraint': {'fill': '#aed6be', 'border': '#94c9ad'}, 'datanode': {'fill': '#fee1a5', 'border': '#fddb91'}, 'graphnode': {'fill': '#b7d2e6', 'border': '#99bcdf'}}, node_color_default='#b6a595', card_corner_radius=0.12, card_port_inner_radius=0.056, card_port_outer_radius=0.096, card_port_ring_radius=0.072, card_depth=0.04, card_line_width=1.0, card_title_font_size=11, card_title_font_family='Arial, Helvetica, sans-serif', card_edge_formula_size=8, graph_px_per_unit=110.0))[source]

Bases: object

Draws one Figure in one plotting framework, in one theme.

A renderer holds the backend figure and the artists drawing the figure’s Results, one artist class per Result class and number of position components (artists); it draws what belongs to a cell or the whole figure itself: axes and colorbars. Self-contained outputs embed states of controls: the figure draws each state, the renderer takes a snapshot() of what was drawn and writes the snapshots into the backend figure (animate(), apply_slider(), apply_selector()).

Parameters:

theme – Colors, fonts and sizes of everything drawn.

artists

{(Result class, dim): Artist class} (class attribute).

Type:

dict

embeddable

Kinds of control a self-contained output embeds (class attribute); the Figure leaves the others in their current state, with a warning.

Type:

tuple of type

max_embedded

Most controls embedded per output (class attribute); None for no limit.

Type:

int or None

theme

The theme.

Type:

Theme

figure

The figure drawn; None before setup().

Type:

Figure or None

backend_figure

The framework’s figure; None before setup().

Type:

object

Notes

Subclasses fill artists and implement every method that raises NotImplementedError.

artists: dict = {}
embeddable: tuple[type, ...] = ()
max_embedded: int | None = None
artist(result_class: type, dim: int) → type[Artist][source]

The artist class drawing a Result class in dim dimensions.

Parameters:
  • result_class – A Result class.

  • dim – Number of position components, 2 or 3.

Returns:

The Artist class.

Return type:

type

Raises:

ValueError – If the renderer cannot draw result_class in dim dimensions.

setup(figure) → None[source]

Bind the renderer to figure and build an empty backend figure with its cell grid.

Parameters:

figure (Figure) – The figure to draw.

Raises:

ValueError – If the renderer already draws another figure.

create_backend_figure(figure)[source]

An empty backend figure with the figure’s cell grid, title and theme.

Parameters:

figure (Figure) – The figure.

Returns:

The backend figure.

Return type:

object

draw(key, result, cell, visible: bool = True) → None[source]

Draw result with the artist of key: create it on first use, update it afterwards.

Parameters:
  • key – Identifies one drawn copy in one cell across states.

  • result (Result) – The Result of the current state.

  • cell (Cell) – The cell drawn into.

  • visible – Whether the artist is shown.

hide(key) → None[source]

Hide the artist of key.

Parameters:

key – A key passed to draw() before.

artist_of(key) → Artist[source]

The artist of key.

Parameters:

key – A key passed to draw() before.

Returns:

The artist.

Return type:

Artist

draw_axes(cell) → None[source]

Apply a cell’s title and position axes: titles, scales (log, trained range, categorical), ticks and equal aspect.

Parameters:

cell (Cell) – The cell.

draw_colorbar(scale, title, ticks, cell, slot: int, visible: bool = True) → None[source]

Draw or update the one colorbar of a ColorScale, beside a cell’s plot area; it is drawn in the scale’s transformed values (log10 for a log scale).

Parameters:
  • scale (ColorScale) – The trained color scale.

  • title (str or None) – Title of the colorbar.

  • ticks (tuple or None) – Tick positions in transformed values and their labels; None for automatic ticks.

  • cell (Cell) – The cell it stands beside (Figure.colorbar_cell).

  • slot – Its place beside the cell, from the plot area (Figure.colorbar_slot).

  • visible – Whether the colorbar is shown.

draw_legend(entries: dict, cell) → None[source]

Draw one legend of the figure, beside a cell’s plot area and its colorbars: one entry per label (as written by the renderer’s text), for the artists drawing it.

Parameters:
  • entries – {label: keys}, in order (see Figure.legends).

  • cell (Cell) – The cell it stands beside.

draw_layout() → None[source]

Size the backend figure and place its cells, titles, colorbars and embedded controls, once everything is drawn in every embedded state: every plot area gets its size from Figure.plot_sizes, and nothing overlaps it.

clear_embeddings() → None[source]

Remove every embedded control from the backend figure.

snapshot(keys, cells, scales) → object[source]

What is drawn now by the artists of keys, the axes of cells and the colorbars of scales; one per embedded state.

Parameters:
  • keys (list) – Artist keys.

  • cells (list of Cell) – Cells whose axes depend on the state.

  • scales (list of ColorScale) – Scales whose colorbars depend on the state.

Returns:

A snapshot for animate(), apply_slider()

and apply_selector().

Return type:

object

animate(time_axis, snapshots) → None[source]

Embed the states of a TimeAxis as an animation.

Parameters:
apply_slider(slider, snapshots) → None[source]

Embed the states of a SliderAxis behind a slider.

Parameters:
apply_selector(selector, snapshots) → None[source]

Embed the choices of a Selector behind a dropdown.

Parameters:
show() → None[source]

Display the backend figure.

save_html(path) → None[source]

Write the backend figure as an interactive HTML file.

Parameters:

path (str or path-like) – Output file path.

save_gif(path, fps: float, frame_weights: list[float]) → None[source]

Write the embedded animation as a looping GIF.

Parameters:
  • path (str or path-like) – Output file path.

  • fps – Frames per second of frames with weight 1.

  • frame_weights – Relative display time per frame.

save_image(path, format, **kwargs) → None[source]

Write the backend figure’s current state as a static image.

Parameters:
  • path (str or path-like) – Output file path.

  • format (str) – Image format, e.g. "png" or "svg".

  • **kwargs – Passed on to the framework’s image export.

class qewton.visualization.renderers.base.Artist[source]

Bases: object

Draws one Result into one cell of a backend figure and keeps it up to date. It sees only Results, cells and the theme, never plots.

Notes

Subclasses implement create(), update() and set_visible(). update() must refresh everything that depends on the state, since outputs embed states by redrawing.

classmethod create(backend_figure, result, cell, theme) → Artist[source]

Draw result into cell.

Parameters:
  • backend_figure (object) – The backend figure.

  • result (Result) – The Result to draw.

  • cell (Cell) – The cell to draw into.

  • theme (Theme) – The renderer’s theme.

Returns:

The new artist.

Return type:

Artist

update(backend_figure, result, cell, theme) → None[source]

Redraw with result, in place.

Parameters:
  • backend_figure (object) – The backend figure.

  • result (Result) – The Result of the current state.

  • cell (Cell) – The cell drawn into.

  • theme (Theme) – The renderer’s theme.

set_visible(backend_figure, visible: bool) → None[source]

Show or hide what the artist draws.

Parameters:
  • backend_figure (object) – The backend figure.

  • visible – Whether it is shown.

qewton.visualization.renderers.base.notebook_html(element: str) → str[source]

HTML showing a figure’s element in a notebook at its own size and resolution: in a box that scrolls horizontally where the figure is wider than the output, as notebooks scale images down to fit it.

Parameters:

element – The figure’s HTML element.

Returns:

The HTML.

Return type:

str

qewton.visualization.renderers.space module

The room beside the plot areas of a figure, for every renderer.

A figure is a grid of plot areas of Figure.plot_sizes; beside every plot area stand the tick labels and titles of its axes, its cell title and the colorbars of the scales whose last cell it is. Their room is estimated, in pixels, from the number of visible characters and the font sizes, so a renderer sizes its figure without measuring texts; the labels of a range are estimated from its ends.

The colorbars a renderer draws are noted in a {key: colorbar} dict (note_colorbar()), with their cell and slot and what they showed in every state drawn; colorbars of one slot share their room. A legend stands right of the colorbars of its cell.

qewton.visualization.renderers.space.TICK_LENGTH = 5

Length of a tick, gap between two elements, margin of the figure, thickness of a colorbar and width of a legend’s symbol with its gap to the label, in pixels.

qewton.visualization.renderers.space.text_width(text: str | None, size: float) → float[source]

The estimated width of a text, in pixels: its visible characters (math as plain text, without sub- and superscript markers).

Parameters:
  • text – A text, possibly with $...$ parts.

  • size – Font size in pixels.

Returns:

The width; 0 without text.

Return type:

float

qewton.visualization.renderers.space.labels_width(labels, size: float) → float[source]

The width of the widest of some texts, in pixels.

Parameters:
  • labels (iterable of str) – The texts.

  • size – Font size in pixels.

Returns:

The width; 0 without texts.

Return type:

float

qewton.visualization.renderers.space.line_height(size: float) → float[source]

The height of one line of text, in pixels.

Parameters:

size – Font size in pixels.

Returns:

The height.

Return type:

float

qewton.visualization.renderers.space.tick_labels(lo: float, hi: float, log: bool = False) → list[str][source]

Labels like those of the ticks of a range: its ends at the precision of a step of about a fifth of it (log: its powers of ten).

Parameters:
  • lo – The range, in data values.

  • hi – The range, in data values.

  • log – Whether the axis is logarithmic.

Returns:

The labels.

Return type:

list of str

qewton.visualization.renderers.space.note_colorbar(colorbars: dict, key, cell, slot: int, title, labels) → None[source]

Note what a colorbar shows in the state drawn.

Parameters:
  • colorbars – The renderer’s {key: colorbar}.

  • key – The colorbar’s key.

  • cell (Cell) – The cell it stands beside.

  • slot – Its place beside the cell.

  • title (str or None) – Its title.

  • labels (iterable of str) – Its tick labels.

qewton.visualization.renderers.space.colorbar_width(colorbar: dict, theme) → float[source]

The room a colorbar takes right of its cell, in pixels: a gap, the bar, its tick labels and its title beside them (turned, one line).

Parameters:
Returns:

The width.

Return type:

float

qewton.visualization.renderers.space.legend_width(labels, theme) → float[source]

The room a legend takes right of its cell, in pixels: a gap, then a symbol and a label per entry.

Parameters:
  • labels (list of str) – Its entries.

  • theme (Theme) – The theme.

Returns:

The width.

Return type:

float

qewton.visualization.renderers.space.OWN_AXES_SIDE = 40

Room a cell laying out its own axes (e.g. parallel coordinates) keeps beside them for the labels of its outer axes, in pixels.

qewton.visualization.renderers.space.grid(figure, colorbars: dict, theme, legends=()) → dict[source]

The room of the grid of a figure: its plot sizes, the gutters of every column and row, and the place of every colorbar and legend beside its cell.

Parameters:
  • figure (Figure) – The trained figure.

  • colorbars – As noted by note_colorbar().

  • theme (Theme) – The theme.

  • legends (list of tuple) – The labels of every legend and the cell it stands beside.

Returns:

widths, heights (the plot sizes), left,

right (per column), top, bottom (per row), all in pixels, colorbars ({key: offset}, the pixels from the right edge of its plot area to the left edge of its bar) and legends ([offset] in the order given, to its left edge).

Return type:

dict

qewton.visualization.renderers.space.title_height(figure, theme) → float[source]

The room of a figure’s title above its grid, in pixels.

Parameters:
  • figure (Figure) – The figure.

  • theme (Theme) – The theme.

Returns:

The height; 0 without a title.

Return type:

float

qewton.visualization.renderers.text module

Texts of the core as renderers display them.

The core writes names of Variables in math mode ($x_1$), everything else as plain text, and joins them freely, e.g. "$t$ = 0.5". A text with an odd number of $ is plain as a whole. segments() splits a text into its plain and math parts; as_plain() turns it into plain text, for displays without math.

qewton.visualization.renderers.text.segments(text: str) → list[tuple[str, bool]][source]

The parts of a text in order.

Parameters:

text – A text, possibly with $...$ parts.

Returns:

(piece, is math); one plain piece if the

number of $ is odd.

Return type:

list of tuple

qewton.visualization.renderers.text.as_plain(text: str | None) → str | None[source]

text without math markers: Greek letters (\alpha) as characters, other commands and braces dropped.

Parameters:

text – A text, possibly with $...$ parts.

Returns:

E.g. "x_1 = 0.5" for "$x_1$ = 0.5".

Return type:

str or None

qewton.visualization.renderers.text.symbols(math: str) → str[source]

A math part with Greek letters (\alpha) as characters, spacing commands as spaces and other commands without their backslash.

Parameters:

math – A math part, without $.

Returns:

The part with symbols replaced.

Return type:

str