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 bysetup(figure), which builds the framework’s figure with the cell grid. The figure callsdraw(key, result, cell, visible)per drawn copy (creating or updating the artist ofkey),hide(key),draw_axes(cell),draw_colorbar(scale, title, ticks, cell, slot, visible)(the cell it stands beside and its place there) anddraw_legend(entries, cell)({label: keys}). To embed a control it takes asnapshot(keys, cells, scales)per state and passes them toanimate,apply_sliderorapply_selector; the class attributesembeddable(kinds of control) andmax_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.artistsmaps (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 |
|---|---|
|
|
|
the figure size and the places of cells, titles, colorbars, legends and embedded controls in paper coordinates |
|
embedded states as the trace and axis properties that differ between them |
|
the artists of the primitive Results |
|
|
|
value bins, segment and triangle coordinates |
|
texts with math as Plotly displays them |
|
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 |
|---|---|
|
|
|
the artists of the primitive Results; |
|
the theme as rcParams (fonts, sizes in points at |
|
texts with math as mathtext displays them, and plain characters |
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 |
|---|---|---|
|
|
– |
|
|
|
|
|
|
|
|
|
|
|
– |
|
|
– |
|
|
|
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¶
- qewton.visualization.renderers.matplotlib package
- Module contents
MatplotlibRendererMatplotlibRenderer.artistsMatplotlibRenderer.embeddableMatplotlibRenderer.max_embeddedMatplotlibRenderer.style()MatplotlibRenderer.text()MatplotlibRenderer.setup()MatplotlibRenderer.draw()MatplotlibRenderer.hide()MatplotlibRenderer.create_backend_figure()MatplotlibRenderer.draw_axes()MatplotlibRenderer.draw_legend()MatplotlibRenderer.draw_colorbar()MatplotlibRenderer.draw_layout()MatplotlibRenderer.clear_embeddings()MatplotlibRenderer.snapshot()MatplotlibRenderer.animate()MatplotlibRenderer.apply_slider()MatplotlibRenderer.show()MatplotlibRenderer.html()MatplotlibRenderer.save_html()MatplotlibRenderer.save_image()MatplotlibRenderer.save_gif()
- Submodules
- qewton.visualization.renderers.matplotlib.primitives module
- qewton.visualization.renderers.matplotlib.style module
- qewton.visualization.renderers.matplotlib.text module
- Module contents
- qewton.visualization.renderers.plotly package
- Module contents
- Submodules
- qewton.visualization.renderers.plotly.camera module
- qewton.visualization.renderers.plotly.card_geometry module
- qewton.visualization.renderers.plotly.embedding module
- qewton.visualization.renderers.plotly.graph module
- qewton.visualization.renderers.plotly.layout module
- qewton.visualization.renderers.plotly.primitives module
- qewton.visualization.renderers.plotly.text module
- qewton.visualization.renderers.plotly.traces module
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:
objectDraws 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 asnapshot()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
Notes
Subclasses fill
artistsand 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.
- 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 (seeFigure.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.
- 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().
- A snapshot for
- Return type:
object
- animate(time_axis, snapshots) None[source]¶
Embed the states of a TimeAxis as an animation.
- Parameters:
time_axis (TimeAxis) – The time axis.
snapshots (list) – One
snapshot()per state.
- apply_slider(slider, snapshots) None[source]¶
Embed the states of a SliderAxis behind a slider.
- Parameters:
slider (SliderAxis) – The slider axis.
snapshots (list) – One
snapshot()per state.
- apply_selector(selector, snapshots) None[source]¶
Embed the choices of a Selector behind a dropdown.
- Parameters:
selector (Selector) – The selector.
snapshots (list) – One
snapshot()per choice.
- save_html(path) None[source]¶
Write the backend figure as an interactive HTML file.
- Parameters:
path (str or path-like) – Output file path.
- class qewton.visualization.renderers.base.Artist[source]¶
Bases:
objectDraws 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()andset_visible().update()must refresh everything that depends on the state, since outputs embed states by redrawing.
- 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:
colorbar – As noted by
note_colorbar().theme (Theme) – The theme.
- 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) andlegends([offset] in the order given, to its left edge).
- Return type:
dict
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 thenumber 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