qewton.visualization package

Module contents

Visualization

Plotting for Qewton data, tables, geometries and computation graphs. A plot binds references into its input to the channels of one kind of mark; controls reduce the dimensions it does not draw; scales map values to positions, colors and arrow lengths. A figure arranges plots in cells and draws them with a renderer (Plotly if installed, else Matplotlib), which owns the theme. Requirements: REQUIREMENTS.md.

Plots and bindings

A data plot takes data, its DataConfiguration and bindings of channels to references: Variables or Axes of the configuration.

  • position= binds a geometry Variable or Axes (all its coordinates), a feature with up to three components, or a tuple of one-component references; it fills x, y, z in order. x=, y=, z= bind one component each and complement position=, e.g. position=X, z=u.

  • Positions from the domain (coordinates of a geometry, index of a batch axis) draw that domain; positions from the values draw every point of the remaining dimensions. Every other dimension of the data must be reduced by a control, else construction raises ValueError.

  • color= binds the color channel, vector= the arrows of a VectorPlot. A tuple in y or z draws one copy per reference.

  • Points outside the domain are not drawn (empty cells, no markers, arrows or cells through them) and do not train the scales: those the point_filter of the geometry excludes (e.g. a rectilinear grid in a domain that is no box), and those where the feature bound to mask= is 0 or NaN (e.g. a domain given per sample). Slices keep both. Graph.visualize(..., mask=port) takes the mask from another port, e.g. the domain mask of a data loader, for every panel.

  • On a product geometry (a meshed space-time domain, a rectilinear grid with the components of its Variable as factors), a control on a factor splits it off; the other factors are drawn. On a 3D grid of x, controls=[SliderAxis(x_2)] draws slices over position=(x_1, x_3).

  • Positions may name parts of the drawn geometry in any order, e.g. x=x_2, y=x_1. A position bound to a controlled factor lies at its current coordinate: SurfacePlot(position=(x_1, x_2, x_3), controls=[SliderAxis(x_3)]) moves the slice through space.

Plot

Draws

HeatmapPlot

a 2D domain flat, colored by a value

SurfacePlot

a surface in 3D: a 2D domain lifted by a height, a surface or the boundary of a volume

LinePlot

a line through a 1D domain, as a graph or a path

ScatterPlot

a marker per point (on the x axis for one position)

BarPlot

a bar per point of a 1D domain

VectorPlot

an arrow per point

ImagePlot

RGB(A) colors on a 2D grid

TableScatter, TableHeatMap, ParallelCoordinatesPlot

rows of a table (columns by name)

GeometryPlot

a geometry without data

GraphPlot

a computation graph

See plots/README.md.

from qewton.visualization import Figure, HeatmapPlot, SliderAxis

plot = HeatmapPlot(data, config, position=X, color=u, controls=[SliderAxis(t)])
Figure(plot).show()

Controls and selectors

Control axes reduce one dimension (a batch axis, a one-dimensional geometry or factor, or a table column) and differ only in presentation:

Control

Shows

SliderAxis

one state, chosen with a slider

TimeAxis

one state at a time as animation frames (one per figure)

FacetAxis

every state side by side, one cell each

OverlayAxis

every state as a copy in one cell

FixedAxis

one fixed state, named in the cell title

A Selector chooses which reference fills a channel, e.g. color=Selector([u, p]) or x=Selector(["lr", "width"]) for table columns. One control or Selector instance passed to several plots links them. States are labeled by their coordinates or categories; animation frames last in proportion to their time step.

Scales

Scale maps values to positions, ColorScale to colors (cmap, reduce for vectors), VectorScale to arrow lengths. Every scale is trained over all states of the controls. Bounds are fixed with vmin and vmax; symmetric=True centers on zero, log=True maps logarithmically and labels by values. One instance shared by several plots gives one range and one colorbar; a Selector gets one color scale per candidate unless color_scale= gives a shared one or a list. Components of one reference, e.g. the coordinates of a geometry, are drawn to one scale. Drawn ranges end at the domain for rasters and surfaces and get a margin for marks; bars start at zero. categorical=True (given to text columns of a table) colors each category with the theme’s palette, with a colorbar step per category.

auto_plot and auto_layout

auto_plot(data, config) chooses a plot type from the kind of value and the drawn domain: a scalar over a 2D domain is a heatmap, over a 1D domain a line, over a volume a surface; a vector with one component per coordinate gives arrows; the coordinates of the domain give points; several scalars become a Selector. Dimensions not drawn get default_control (a slider); controls= sets them explicitly. A control on one coordinate of a grid gives a heatmap of the slice; plot_type=SurfacePlot draws the slice in space. plot_type=, value=, bindings and plot options (e.g. z=u) take part in the choice; if nothing fits, the error names every plot type tried.

AutoPlots(controls) builds several plots with auto_plot (add(data, config, ...)) that share their controls: a control made for one plot reaches every later plot whose data has its axes (by identity) or Variable, e.g. one slider over the batch of a model output and of its data. Graph.visualize and DataNode.visualize build their plots so.

auto_layout(plots) overlays plots that read well together (no two show values the same way at the points of the domain, e.g. arrows over a heatmap) and places the others side by side with linked axes.

Figure and layout

Figure(layout, renderer=None, title=None) takes a plot, a list of plots or nested Overlay/Row/Column. Plots in one Overlay share its position axes (PositionAxis(scale=, ticks=, title=)); facets repeat a cell.

Output

Controls

draw()

current states; returns the renderer’s figure

show(), save_html()

every control embedded (slider, animation, dropdown)

save_png(), save_svg()

current states

save_gif()

the animation of the TimeAxis

DashApplication.create()

sliders and selectors connected to widgets, the rest embedded

WidgetApplication.create()

sliders, animations and selectors connected to widgets

Per plot, one control axis is embedded; next to it one Selector, else several Selectors of different channels. Controls that would overwrite each other, or that the renderer does not embed, keep their current state, with a warning. Cells sharing position axes zoom, pan and rotate together.

The size of a figure follows from its plots: every plot area gets the theme’s plot box (plot_width x plot_height), a fixed aspect fitted into it; titles, tick labels, colorbars and legends get room beside it. A colorbar stands right of the last cell of its scale, as tall as its plot area; a legend, only where it tells two entries or more apart, right of the last of the cells with these entries. Every output shows the figure at its size; inline in a notebook, a wider figure scrolls.

Renderers

PlotlyRenderer(theme=DEFAULT_THEME, mathjax=True) and MatplotlibRenderer(theme=DEFAULT_THEME, usetex=False, dpi=100); what each draws and embeds: renderers/README.md.

Applications

DashApplication.create(figure) serves a Plotly figure as a Dash app; start it with app.run(). WidgetApplication.create(figure) shows a Matplotlib figure in a notebook (needs ipywidgets and ipympl).

Themes

Theme sets colors, fonts and colormaps; LIGHT_THEME (default) and DARK_THEME are given; cmaps holds colormap roles and colormaps. See themes/README.md.

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

Figure(plot, renderer=PlotlyRenderer(theme=DARK_THEME)).show()

Graph integration

  • graph.visualize(port, ...) evaluates a port on a mesh of its samplers’ domains and returns a layout for Figure. With reference= (data with reference_config, another port, or a function of the points) it draws reference, prediction and error= with one color scale and shared controls; variables= narrows the output to some of its Variables.

  • data_node.visualize() draws every output of a data node.

  • PlotNode draws whatever data reaches it in a graph.

layout = graph.visualize(model.output_ports[0], reference=exact, controls=[TimeAxis(t)])
Figure(layout).show()

See DECISIONS.md for design decisions.

Subpackages

Submodules

qewton.visualization.auto module

Automatic choice of a plot type and its bindings from a DataConfiguration.

auto_plot() decides in three steps, without knowing any geometry class:

  1. The drawn domain: the GeometryAxes not reduced by a control (1D factors of a product, or 1D GeometryAxes, are split off where needed), else the first other axis. Every axis not drawn gets a control.

  2. The kind of value, from the quantities of the FeatureAxes’ Variable.

  3. The plot type: the first entry of CHOICES for that kind whose type declares that it draws the domain (DataPlot.supports()).

qewton.visualization.auto.MAX_DRAWN_DIM = 3

Highest dimension a drawn domain can have.

class qewton.visualization.auto.Kind(*values)[source]

Bases: Enum

What the plotted value is, relative to the drawn domain.

SCALAR

One value per point (or a Selector of such values).

VECTOR

A vector with one component per coordinate of the domain.

COORDINATES

The coordinates of the domain itself, e.g. sampled points or the grid of a data loader; drawn as the points of the domain (on the x axis for a 1D domain).

VALUES

Values without a domain, drawn in value space; every point of the data is one element.

SCALAR = 1
VECTOR = 2
COORDINATES = 3
VALUES = 4
class qewton.visualization.auto.Choice(plot_type: type[DataPlot], bindings: dict)[source]

Bases: object

A plot type with its bindings; placeholders stand for the drawn domain (D), the value (V, or V0/V1 for two) and the controlled coordinate of the drawn quantity (C, e.g. x_3 of a slice through a grid of x).

plot_type: type[DataPlot]
bindings: dict
qewton.visualization.auto.CHOICES: dict[Kind, list[Choice]] = {Kind.COORDINATES: [Choice(plot_type=<class 'qewton.visualization.plots.data.scatter.ScatterPlot'>, bindings={'position': <_Placeholder.DOMAIN: 1>})], Kind.SCALAR: [Choice(plot_type=<class 'qewton.visualization.plots.data.heatmap.HeatmapPlot'>, bindings={'position': <_Placeholder.DOMAIN: 1>, 'color': <_Placeholder.VALUE: 2>}), Choice(plot_type=<class 'qewton.visualization.plots.data.line.LinePlot'>, bindings={'x': <_Placeholder.DOMAIN: 1>, 'y': <_Placeholder.VALUE: 2>}), Choice(plot_type=<class 'qewton.visualization.plots.data.bar.BarPlot'>, bindings={'x': <_Placeholder.DOMAIN: 1>, 'y': <_Placeholder.VALUE: 2>}), Choice(plot_type=<class 'qewton.visualization.plots.data.surface.SurfacePlot'>, bindings={'position': <_Placeholder.DOMAIN: 1>, 'color': <_Placeholder.VALUE: 2>}), Choice(plot_type=<class 'qewton.visualization.plots.data.surface.SurfacePlot'>, bindings={'position': <_Placeholder.DOMAIN: 1>, 'z': <_Placeholder.CONTROLLED: 5>, 'color': <_Placeholder.VALUE: 2>}), Choice(plot_type=<class 'qewton.visualization.plots.data.scatter.ScatterPlot'>, bindings={'position': <_Placeholder.DOMAIN: 1>, 'color': <_Placeholder.VALUE: 2>})], Kind.VALUES: [Choice(plot_type=<class 'qewton.visualization.plots.data.scatter.ScatterPlot'>, bindings={'x': <_Placeholder.FIRST: 3>, 'y': <_Placeholder.SECOND: 4>}), Choice(plot_type=<class 'qewton.visualization.plots.data.scatter.ScatterPlot'>, bindings={'position': <_Placeholder.VALUE: 2>})], Kind.VECTOR: [Choice(plot_type=<class 'qewton.visualization.plots.data.vector.VectorPlot'>, bindings={'position': <_Placeholder.DOMAIN: 1>, 'vector': <_Placeholder.VALUE: 2>, 'color': <_Placeholder.VALUE: 2>})]}

Plot types per kind of value, in order of preference.

qewton.visualization.auto.auto_plot(data, data_config: DataConfiguration, plot_type: type[DataPlot] | None = None, *, value: Variable | Selector | None = None, controls: list[ControlAxis] = (), default_control: type[ControlAxis] = <class 'qewton.visualization.axes.SliderAxis'>, color_scale: ColorScale | None = None, vector_scale: VectorScale | None = None, **plot_kwargs) → DataPlot[source]

Build a plot for data, choosing its type and bindings from data_config (see the module documentation).

Parameters:
  • data – Tensor described by data_config, of any backend.

  • data_config – Its DataConfiguration, with a FeatureAxes of a named Variable.

  • plot_type – Restricts the choice to this plot type.

  • value – What to draw: a Variable of the FeatureAxes, or a Selector of them (e.g. one shared by several plots); None for every quantity of the FeatureAxes.

  • controls – Control axes for chosen dimensions, e.g. [TimeAxis(t)]; a control on a factor of a product splits it off.

  • default_control – Control axis class for every other dimension not drawn.

  • color_scale – Passed to the plot’s color channel.

  • vector_scale – Passed to a VectorPlot.

  • **plot_kwargs – Further arguments of the plot type, e.g. title; bindings among them (e.g. z=u) override the chosen ones.

Returns:

The plot.

Return type:

DataPlot

Raises:

ValueError – If the data has no named feature Variable, the drawn domain or the value is ambiguous, no plot type (or not plot_type) fits, or color_scale / vector_scale is given for a plot without that channel.

class qewton.visualization.auto.AutoPlots(controls: list[ControlAxis] = ())[source]

Bases: object

Plots of one visualization built by auto_plot(), sharing their controls: a control made for one plot, e.g. a default slider over a batch axis, is passed to every later plot whose data has its axes or Variable. An axes is recognized by identity, as matching makes equal axes one object.

Parameters:

controls – Control axes for chosen dimensions, passed to every plot whose data has them.

plots

The plots built so far, in order.

Type:

list[DataPlot]

add(data, data_config: DataConfiguration, *args, **kwargs) → DataPlot[source]

Build the next plot with auto_plot().

Parameters:
  • data – The data, as for auto_plot().

  • data_config – Its DataConfiguration.

  • *args – Passed to auto_plot().

  • **kwargs – Passed to auto_plot(), except controls.

Returns:

The plot.

Return type:

DataPlot

check_controls() → None[source]

Check that every given control steps through the data of a plot.

Raises:

ValueError – If a given control refers to the data of no plot.

qewton.visualization.axes module

Axes of a drawing and controls.

Position axes (x, y, z) of an Overlay and control axes together span the dimensions of a drawing: a plot draws the dimensions of its data that its positions cover and reduces every other one with a control axis. A Selector lets the viewer choose which reference fills a channel.

“Axis” here is a dimension of the drawing; the tensor axes of a DataConfiguration are Axes.

qewton.visualization.axes.POSITION_CHANNELS = ('x', 'y', 'z')

The position channels, in the order a position with several components fills them.

class qewton.visualization.axes.PositionAxis(scale: Scale | None = None, ticks: list[float] | None = None, title: str | None = None)[source]

Bases: object

A coordinate axis of an Overlay: x, y or z, by its keyword there.

Parameters:
  • scale – Scale of the axis; a linear one if None. Overlays sharing a Scale instance get one range.

  • ticks – Tick positions, or None for automatic ones.

  • title – Title; None derives it from the references bound to the axis (one shared reference: its name, different ones: none).

scale

Scale of the axis.

Type:

Scale

ticks

Tick positions.

Type:

list of float or None

title

The explicit title.

Type:

str or None

class qewton.visualization.axes.Control(init_state: int = 0)[source]

Bases: object

Something with a state the viewer sets, or that is set for them.

Plots receiving the same instance share its state and its widget.

state

The current state, an index into states.

Type:

int

states

All states.

Type:

list of int

trained_states

The states scales are trained over.

Type:

list of int

name

Display name, e.g. for a widget label.

Type:

str

Notes

Subclasses implement states, name and label().

property state: int
property states: list[int]
property trained_states: list[int]
property name: str
label(state: int) → str[source]

Display text of state, e.g. for a slider step.

class qewton.visualization.axes.ControlAxis(variable_or_axes: Variable | Axes | str, init_state: int = 0, title: str | None = None)[source]

Bases: Control

Reduces one dimension of the data to its states.

Every plot it is passed to resolves it against its data (resolve()); plots sharing an instance must agree on the size.

Parameters:
  • variable_or_axes – The dimension: an Axes of one tensor axis, the Variable of a one-dimensional geometry (e.g. time), or the name of a table column (one state per value).

  • init_state – Initial state.

  • title – Title, e.g. of the widget; derived from variable_or_axes if None.

variable_or_axes

The dimension.

Type:

Variable or Axes or str

coordinates

Coordinate of each state, e.g. the time of each time step; None without coordinates.

Type:

numpy.ndarray or None

labels

Display text of each state, e.g. the categories of a table column; None to show the coordinates.

Type:

list of str or None

copies

Whether the plot draws one copy per state instead of one state at a time (class attribute).

Type:

bool

copies = False
coordinates: ndarray | None
labels: list[str] | None
resolve(size: int, coordinates: ndarray | None = None, labels: list[str] | None = None) → None[source]

Bind the axis to a dimension of size states.

Parameters:
  • size – Number of states of the dimension in a plot’s data.

  • coordinates – Coordinate of each state, if the dimension has coordinates.

  • labels – Display text of each state, if the states are named (e.g. categories).

Raises:

ValueError – If another plot resolved it to a different size, or the initial state is out of range.

property states: list[int]
property name: str
label(state: int) → str[source]

Display text of state: its label, else its coordinate (4 significant digits), else the index.

class qewton.visualization.axes.SliderAxis(variable_or_axes: Variable | Axes | str, init_state: int = 0, title: str | None = None)[source]

Bases: ControlAxis

One state at a time, chosen with a slider.

class qewton.visualization.axes.TimeAxis(variable_or_axes: Variable | Axes | str, init_state: int = 0, title: str | None = None, duration: int = 500)[source]

Bases: ControlAxis

One state at a time, played as frames; at most one per figure.

Parameters:
  • variable_or_axes – As for ControlAxis.

  • init_state – As for ControlAxis.

  • title – As for ControlAxis.

  • duration – Mean display time per frame in milliseconds.

duration

Mean display time per frame in milliseconds.

Type:

int

frame_weights() → list[float][source]

Relative display time per frame, with mean 1: proportional to the time until the next frame if the states have coordinates, equal otherwise.

Returns:

One weight per state.

Return type:

list of float

class qewton.visualization.axes.FacetAxis(variable_or_axes: Variable | Axes | str, orientation: str = 'col', title: str | None = None)[source]

Bases: ControlAxis

Every state side by side: the overlay is repeated per state within its cell; the copies share the overlay’s axes and scales.

Parameters:
  • variable_or_axes – As for ControlAxis.

  • init_state – As for ControlAxis.

  • title – As for ControlAxis.

  • orientation – "row" or "col": whether the copies are stacked or placed side by side.

Raises:

ValueError – If orientation is neither "row" nor "col".

orientation

"row" or "col".

Type:

str

class qewton.visualization.axes.OverlayAxis(variable_or_axes: Variable | Axes | str, init_state: int = 0, title: str | None = None)[source]

Bases: ControlAxis

Every state at once in the same overlay, one drawn copy per state, each with a legend entry. The copies get categorical colors unless the plot binds a color.

copies = True
property trained_states: list[int]
class qewton.visualization.axes.FixedAxis(variable_or_axes: Variable | Axes | str, init_state: int = 0, title: str | None = None)[source]

Bases: ControlAxis

One fixed state, named in the title of the cell.

Raises:

ValueError – When state is set to another state.

property state: int
property trained_states: list[int]
class qewton.visualization.axes.Selector(candidates: list[Variable] | list[str], init_state: int = 0)[source]

Bases: Control

Alternative references for one channel, chosen by the viewer; used in place of a reference, e.g. color=Selector([u, p]). Only the chosen one is drawn, and titles derived from it follow the choice.

Parameters:
  • candidates – At least two Variables, or two names of table columns.

  • init_state – Index of the initial choice.

Raises:

ValueError – With fewer than two candidates.

candidates

The candidates.

Type:

list of Variable or str

selected

The chosen candidate.

Type:

Variable or str

property selected: Variable | str
property states: list[int]
property name: str
label(state: int) → str[source]

Display text of state: the candidate’s title (math mode for a Variable).

qewton.visualization.figure module

The Figure, which arranges plots in a grid of cells and draws them.

class qewton.visualization.figure.Cell(row: int, col: int, overlay: Overlay, facet_states: dict = <factory>)[source]

Bases: object

One drawn copy of an Overlay in the figure grid.

Parameters:
  • row – Grid row, 1-indexed.

  • col – Grid column, 1-indexed.

  • overlay – The overlay drawn here.

  • facet_states – {FacetAxis: state} of this copy.

dim

Number of position components: 2 or 3, or 0 for plots that lay out their own axes (e.g. parallel coordinates).

Type:

int

axes

{channel: PositionAxis} of the overlay.

Type:

dict

title

The overlay’s title, followed by the facet states and the states of fixed axes, e.g. "u, t = 0.5".

Type:

str or None

scaled_channels

The channels drawn to one scale.

Type:

tuple of str

aspect

Height over width of the plot area of a 2D cell drawing x and y to one scale, else None.

Type:

float or None

box_aspect

Relative lengths of the x, y and z sides of a 3D cell’s box, else None.

Type:

tuple of float or None

row: int
col: int
overlay: Overlay
facet_states: dict
property dim: int
property axes: dict[str, PositionAxis]
property scaled_channels: tuple[str, ...]
property aspect: float | None
property box_aspect: tuple[float, float, float] | None
property title: str | None
axis_title(channel: str) → str | None[source]

The title of a position axis; see axis_title().

axis_range(channel: str) → tuple[float, float] | None[source]

The drawn range of a position axis: its scale’s range, widened on both sides by the overlay’s margin of its span (in log space for a log scale).

Parameters:

channel – "x", "y" or "z".

Returns:

(lo, hi); None for a categorical

axis, without a range or for an empty one.

Return type:

tuple of float or None

axis_ticks(channel: str) → tuple | None[source]

The ticks of a position axis; see axis_ticks().

class qewton.visualization.figure.Figure(plots: Plot | Layout | list[Plot], renderer: Renderer | None = None, title: str | None = None)[source]

Bases: object

Draws plots, arranged in a layout, with a renderer.

Each overlay of the layout is one cell of the grid, repeated per state of its facet axes. Drawing trains all scales over every state of the plots’ controls, then draws one artist per Result into its cell, the position axes of every cell and one colorbar per ColorScale.

A control is shown in one of two ways: connected to a widget of an application, which sets its state and draws again, or embedded into the output, which then holds every state (draw() with embedded). An embedded Selector draws every candidate and shows the chosen one. Per plot at most one control axis and one Selector are embedded, since their states would overwrite each other.

Parameters:
  • plots – A Plot, a Layout, or a list of plots (a Row).

  • renderer – The renderer drawing and exporting the figure, used by this figure only; a new default renderer if None.

  • title – Title of the figure.

Raises:

ValueError – With more than one TimeAxis, an overlay with more than one facet axis per orientation, or a renderer already drawing another figure.

renderer

The renderer.

Type:

Renderer

title

The title.

Type:

str or None

plots

Every plot, in reading order.

Type:

list of Plot

cells

The cells of the grid.

Type:

list of Cell

grid_shape

Number of grid rows and columns.

Type:

tuple of int

controls

Every control of the plots (control axes and selectors), each shared instance once.

Type:

list of Control

color_scales

Every color scale of the plots, each shared instance once.

Type:

list of ColorScale

backend_figure

The renderer’s figure.

Type:

object

property backend_figure
property controls: list[Control]
property color_scales: list[ColorScale]
plot_sizes() → tuple[list[float], list[float]][source]

The size of the plot areas, in pixels: the width of every grid column and the height of every row. A cell of a fixed aspect fits it into the theme’s plot box (plot_width x plot_height), any other fills the box; a column is as wide as its widest cell, a row as tall as its tallest, an empty one takes no space. Follows the trained scales.

Returns:

Column widths and row heights.

Return type:

tuple

legends() → list[tuple[dict, Cell]][source]

The legends of the figure as drawn last: the entries of every cell are the labels of its visible Results with a legend entry (Result.legend_entry), each once, in drawing order; cells of equal entries share one legend beside the last of them, as cells of a color scale share its colorbar. Fewer than two entries tell nothing apart and get none; nor does a theme without legends.

Returns:

Per legend, {label: keys} (the artists

drawing every entry, in all its cells) and the cell it stands beside.

Return type:

list of tuple

cell_at(row: int, col: int) → Cell | None[source]

The cell at a grid position, or None for an empty position.

Parameters:
  • row – Grid row, 1-indexed.

  • col – Grid column, 1-indexed.

Returns:

The cell.

Return type:

Cell or None

colorbar_cell(scale: ColorScale) → Cell[source]

The cell the colorbar of scale stands beside: the last of its cells, rightmost, then topmost.

Parameters:

scale – A color scale of the figure.

Returns:

The cell.

Return type:

Cell

colorbar_slot(scale: ColorScale) → int[source]

The place of the colorbar of scale beside its cell, counted from the plot area: one per plot with a colorbar there, in drawing order; the scales of one plot (e.g. of the candidates of a Selector) are never shown together and share it.

Parameters:

scale – A color scale of the figure.

Returns:

The slot, from 0.

Return type:

int

cells_of(scale: ColorScale) → list[Cell][source]

The cells with a plot using scale.

Parameters:

scale – A color scale of the figure.

Returns:

The cells, in grid order.

Return type:

list of Cell

color_title(scale: ColorScale) → str | None[source]

The colorbar title of scale: the color title all plots drawing with it share in their current states, else None.

Parameters:

scale – A color scale of the figure.

Returns:

The title.

Return type:

str or None

color_ticks(scale: ColorScale) → tuple[list[float], list[str]] | None[source]

The colorbar ticks of scale, in its transformed values: the ticks all plots drawing with it give it (e.g. categories, also while it is not shown), else those of a log scale (values at their log10), else None for automatic ticks.

Parameters:

scale – A color scale of the figure.

Returns:

Positions and labels.

Return type:

tuple or None

draw(embedded: list[Control] = ())[source]

Train the scales and draw every plot, axis, colorbar and legend in the current states of the controls; embed the states of embedded; then lay the figure out, with room for what every embedded state shows. Artists of an earlier call are updated, not recreated.

Parameters:

embedded – Controls whose states the output holds; facet, overlay and fixed axes need no embedding. TimeAxes come first, then SliderAxes, then Selectors. A control is skipped with a warning if the renderer does not embed its kind (Renderer.embeddable), if the renderer’s limit is reached (max_embedded), or if it would overwrite an earlier one on a common plot. A plot embeds one control axis; next to it one Selector, drawn as every candidate of which the chosen one is shown. Without one, it embeds several Selectors of different channels, each by its data.

Returns:

The renderer’s figure (backend_figure).

Return type:

object

redraw() → None[source]

Draw every plot, axis and colorbar in the current states of the controls, without training the scales again.

show() → None[source]

Draw the figure with every control embedded and display it.

save_html(path) → None[source]

Draw the figure with every control embedded and write it as an interactive HTML file.

Parameters:

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

save_png(path, **kwargs) → None[source]

Draw the figure in its current states and write a PNG image.

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

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

save_svg(path, **kwargs) → None[source]

Draw the figure in its current states and write an SVG image.

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

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

save_gif(path, fps: float = 10) → None[source]

Draw the figure with its TimeAxis embedded and write the animation as a looping GIF; other controls stay in their current states.

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

  • fps – Frames per second of equally spaced time steps; each frame is shown in proportion to its time step (see frame_weights()).

Raises:

ValueError – If the figure has no TimeAxis.

qewton.visualization.layout module

class qewton.visualization.layout.Layout[source]

Bases: object

Base class for anything that places Plots into a Figure. Figure normalizes whatever it is given into one of these before drawing.

property plots: list[Plot]

Every Plot this layout contains, flattened, in reading order.

Returns:

The contained plots.

Return type:

list[Plot]

class qewton.visualization.layout.Overlay(*plots: Plot, x: PositionAxis | None = None, y: PositionAxis | None = None, z: PositionAxis | None = None, title: str | None = None)[source]

Bases: Layout

Plots drawn into one cell, in one coordinate system.

Its dimension is the plots’ one. Plots showing values by color at the points of their domain are drawn first, the others on top, each group in the given order. Facet axes of its plots repeat it within its cell; the copies share its position axes, and plots without facet axes are drawn in every copy.

Parameters:
  • *plots – The plots, all of one dimension; those with facet axes all with the same.

  • x – The position axes; new linear ones if None.

  • y – The position axes; new linear ones if None.

  • z – The position axes; new linear ones if None.

  • title – Title of the cell; None joins the plots’ titles.

Raises:

ValueError – If the plots differ in dimension, or two plots have different facet axes.

plots

The plots, in drawing order.

Type:

list of Plot

axes

{channel: PositionAxis} for its dimension.

Type:

dict

dim

2 or 3; None while empty.

Type:

int or None

facets

The facet axes of its plots.

Type:

list of FacetAxis

scaled_channels

The channels every plot draws to one scale.

Type:

tuple of str

margin

The margin of the drawn position ranges: 0 if any plot ends at its domain (e.g. arrows over a heatmap), else the largest of its plots.

Type:

float

title

Title of the cell.

Type:

str or None

property plots: list[Plot]

Every Plot this layout contains, flattened, in reading order.

Returns:

The contained plots.

Return type:

list[Plot]

property dim: int | None
property axes: dict[str, PositionAxis]
property facets: list[FacetAxis]
property scaled_channels: tuple[str, ...]
property margin: float
property title: str | None
axis_title(channel: str) → str | None[source]

The title of a position axis: the explicit one, else the title all plots give it, else None.

Parameters:

channel – "x", "y" or "z".

Returns:

The title.

Return type:

str or None

axis_ticks(channel: str) → tuple[list[float], list[str] | None] | None[source]

The ticks of a position axis: the explicit positions, else the ticks the plots give it if they agree, else None for automatic ones.

Parameters:

channel – "x", "y" or "z".

Returns:

Tick positions and their labels (None to label

them with their values).

Return type:

tuple or None

qewton.visualization.layout.auto_layout(plots: list[Plot]) → Overlay | Row[source]

Place plots in one Overlay where they read well together, else side by side.

Plots of one dimension that give their position axes the same titles share an Overlay if no two of them show values at the points of the domain the same way (see point_encoding), e.g. arrows of u over a heatmap of p, or lines of one quantity from several sources. Otherwise they are placed side by side, e.g. two heatmaps or two vector fields of a reference and a prediction; they share their position axes there, so their ranges, zoom and camera go together.

Parameters:

plots – The plots, at least one.

Returns:

An Overlay of all plots, or a Row of them.

Return type:

Overlay or Row

class qewton.visualization.layout.Row(*items: Plot | Layout)[source]

Bases: _MultiItemLayout

Places its items side by side, left to right.

Parameters:

*items (Plot | Layout) – The plots or layouts to place, in order.

class qewton.visualization.layout.Column(*items: Plot | Layout)[source]

Bases: _MultiItemLayout

Places its items one above another, top to bottom.

Parameters:

*items (Plot | Layout) – The plots or layouts to place, in order.

qewton.visualization.layout.normalize(item: Plot | Layout) → list[list[Overlay]][source]

Normalizes a Plot or Layout into a rectangular grid of Overlays.

Parameters:

item (Plot | Layout) – The plot or layout to normalize.

Returns:

Rows of Overlays. Irregular grids (e.g. a

Column mixing single plots with multi-column Rows) are padded with empty Overlays, not spanned.

Return type:

list[list[Overlay]]

Raises:

TypeError – If item is neither a Plot nor a Layout.

qewton.visualization.nodes module

class qewton.visualization.nodes.PlotNode(plot_type: type | None = None, show: bool = True, save_path: str | None = None, name: str | None = None, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **plot_kwargs)[source]

Bases: GraphAwareNode[TensorType]

Graph-embedded sink: draws (and optionally saves) whatever array-like data reaches it, passing nothing downstream.

plot_type=None (default) accepts any shape and picks a Plot via auto_plot(). Given a specific plot type, this is a plain pass-through to auto_plot(x, config, plot_type=plot_type, **plot_kwargs) - plot_kwargs must supply that type’s required roles directly, exactly as constructing it directly would.

The input port’s own DataConfiguration is deliberately a wildcard (EllipsisAxes): auto_plot needs the unified DataConfiguration (which depends on whatever this node ends up connected to) to know what’s actually plottable, and ports are typed once, before any connection exists - narrowing it upfront isn’t possible, so an incompatible connection is only ever caught at forward() time, via auto_plot’s/the underlying Plot’s own validation.

ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
build(graph) → None[source]

Create what the node computes with, using the graph it is part of.

Parameters:

graph (Graph) – The graph being set up.

forward(x: Annotated[TensorType, ..., Number, ()])[source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

qewton.visualization.references module

Names of references into data: Variables and Axes of a DataConfiguration, or names of table columns, as shown in titles.

qewton.visualization.references.title_of(reference: Variable | Axes | str) → str | None[source]

The title naming a reference.

Parameters:

reference – A Variable, an Axes of a DataConfiguration, or the name of a table column.

Returns:

The Variable’s math name (for a GeometryAxes, the one

of its geometry’s variable); a column name as it is; None for an Axes without a variable, e.g. a BatchAxes.

Return type:

str or None

qewton.visualization.references.component_titles(reference: Variable | Axes, n: int) → list[str | None][source]

Titles of the n components of a reference, e.g. $x$ and $y$ for Variable("x", 1) * Variable("y", 1), $x_1$ and $x_2$ for Variable("x", 2).

Parameters:
  • reference – A Variable, or an Axes of a DataConfiguration.

  • n – Number of components.

Returns:

One title per component; None where the

reference has no name.

Return type:

list of str or None

qewton.visualization.scales module

Scales: how data values are mapped to visual values.

class qewton.visualization.scales.Scale(vmin: float | None = None, vmax: float | None = None, log: bool = False, symmetric: bool = False, categorical: bool = False)[source]

Bases: object

Maps data values to visual values (positions, colors, lengths).

Its range is trained from every value bound to it, over all control states, before a figure is drawn; explicit bounds win. A shared instance links whatever uses it: one range for axes of several overlays, one colorbar for several plots.

Parameters:
  • vmin – Fixed lower bound.

  • vmax – Fixed upper bound.

  • log – Logarithmic mapping. Values that are not positive are ignored when training.

  • symmetric – Range symmetric around 0, e.g. for errors.

  • categorical – Values are categories, e.g. the index of a batch axis.

Raises:

ValueError – If log and symmetric are both set, or a fixed bound of a log scale is not positive.

vmin

Fixed lower bound.

Type:

float or None

vmax

Fixed upper bound.

Type:

float or None

log

Logarithmic mapping.

Type:

bool

symmetric

Range symmetric around 0.

Type:

bool

categorical

Values are categories.

Type:

bool

range

(lo, hi) from the fixed bounds and the trained values, made symmetric if requested; None while neither is known.

Type:

tuple of float or None

reset() → None[source]

Forget the trained range, before the scale is trained anew.

train(values) → None[source]

Extend the trained range to cover values, ignoring NaN (and, for a log scale, values that are not positive).

Parameters:

values (array_like) – Values bound to this scale.

property range: tuple[float, float] | None
transform(values) → ndarray[source]

Map values into the scale’s space: log10 for a log scale (NaN where not positive), unchanged otherwise. For renderers whose framework cannot map a log scale itself, e.g. for colors.

Parameters:

values (array_like) – Values bound to this scale.

Returns:

The transformed values, as floats.

Return type:

numpy.ndarray

inverse(values) → ndarray[source]

Map values of the scale’s space back: the inverse of transform().

Parameters:

values (array_like) – Transformed values.

Returns:

The values, as floats.

Return type:

numpy.ndarray

qewton.visualization.scales.log_ticks(lo: float, hi: float) → tuple[list[float], list[str]][source]

Ticks of a log scale: all leading digits times powers of ten within the range if 1, 2 and 5 give fewer than three; else the first of 1, 2 and 5, 1 and 3, or only the powers of ten (thinned) that gives at most six, so the labels fit an axis of the theme’s plot size.

Parameters:
  • lo – The range in log10 space.

  • hi – The range in log10 space.

Returns:

The tick positions in log10 space and their labels.

Return type:

tuple

qewton.visualization.scales.color_range(scale: Scale) → tuple[float, float][source]

The trained range of a scale in its transformed space (log10 for a log scale), widened if degenerate; a categorical scale spans its codes ±0.5, so every category is the center of its band.

Parameters:

scale – The trained scale.

Returns:

(lo, hi) with lo < hi; (0, 1) without a

range.

Return type:

tuple of float

class qewton.visualization.scales.Reduce(*values)[source]

Bases: Enum

How a value with several components is reduced to one for a scalar channel such as color.

MAGNITUDE

The Euclidean norm of the components.

MAGNITUDE = 1
class qewton.visualization.scales.ColorScale(cmap=None, reduce: Reduce | int = Reduce.MAGNITUDE, vmin: float | None = None, vmax: float | None = None, log: bool = False, symmetric: bool = False, categorical: bool = False)[source]

Bases: Scale

Maps values to colors; one colorbar is drawn per instance.

Parameters:
  • cmap (ColormapRole or QewtonColormap or str or list, optional) – A colormap role (e.g. cmaps.diverging), resolved against the figure’s theme, a qewton colormap, or a renderer-native colormap. None uses the theme’s palette for a categorical scale, else its sequential colormap.

  • reduce – How a value with several components becomes one color value: Reduce.MAGNITUDE or the index of a component.

  • vmin – As for Scale.

  • vmax – As for Scale.

  • log – As for Scale.

  • symmetric – As for Scale.

  • categorical – As for Scale.

cmap

The colormap.

Type:

object or None

reduce

The reduction of several components.

Type:

Reduce or int

colorscale(theme)[source]

The colormap of this scale, resolved against a theme: one band per category for a categorical scale (its codes, centered on them), else continuous.

Parameters:

theme (Theme) – The theme resolving colormap roles.

Returns:

See resolve_cmap().

Return type:

str or list

reduce_components(values: ndarray) → ndarray[source]

Reduce values of shape (n, k) to one value per element.

Parameters:

values – One row per element, one column per component.

Returns:

Shape (n,).

Return type:

numpy.ndarray

class qewton.visualization.scales.VectorScale(length: float | None = None, normalize: bool = False, vmax: float | None = None)[source]

Bases: Scale

Maps vectors to arrows: trained on the vector magnitudes, it scales the longest vector to length (untrained: the longest of those it maps).

Parameters:
  • length – Length of the longest arrow in data units; None for the typical point spacing of the drawn positions.

  • normalize – Draw every arrow with the same length, showing only the direction.

  • vmax – Fixed largest magnitude, drawn with length.

length

Length of the longest arrow.

Type:

float or None

normalize

Whether every arrow has the same length.

Type:

bool

arrows(vectors: ndarray, spacing: float) → ndarray[source]

The arrows of vectors, in data units.

Parameters:
  • vectors – Shape (n, dim).

  • spacing – Typical point spacing of the drawn positions; the length of the longest arrow if length is None.

Returns:

Shape (n, dim).

Return type:

numpy.ndarray