quimb.tensor.drawing

Functionailty for drawing tensor networks.

Attributes

Functions

autocorrect_kwargs([func, valid_kwargs])

A decorator that suggests the right keyword arguments if you get them

check_opt(name, value, valid)

Check whether value takes one of valid options, and raise an

draw_tn(tn[, color, show_inds, show_tags, ...])

Plot this tensor network as a networkx graph using matplotlib,

parse_dict_to_tids_or_inds(spec, tn[, default])

Parse a dictionary possibly containing a mix of tags, tids and inds, to

_add_legend_matplotlib(ax, colors, legend, ...)

_draw_matplotlib(edges, nodes, *[, colors, ...])

_linearize_graph_data(G[, multi_tag_style])

_draw_matplotlib3d(G, **kwargs)

_draw_plotly(G, **kwargs)

_normalize_positions(pos)

_rotate(xy, theta)

Return a rotated set of points.

_span(xy)

Return the vertical span of the points.

_massage_pos(pos[, nangles, flatten])

Rotate a position dict's points to cover a small vertical span

phyllotaxis_points(n)

  1. Kogan, "A New Computationally Efficient Method for Spacing Points on

layout_single_tensor(tn[, dim])

Manually layout indices around a tensor either in a circle or sphere.

layout_networkx(G[, layout, pos0, fixed, dim])

layout_pygraphviz(G[, layout, pos0, fixed, dim, ...])

get_positions(tn, G, *[, dim, fix, layout, ...])

get_colors(color[, custom_colors, alpha])

Generate a sequence of rgbs for tag(s) color.

to_rgba_str(color[, alpha])

auto_color_html(s)

Automatically hash and color a string for HTML display.

visualize_tensor(tensor, **kwargs)

Visualize all entries of a tensor, with indices mapped into the plane

choose_squarest_grid(x)

visualize_tensors(tn[, mode, r, r_scale, figsize])

Visualize all the entries of every tensor in this network.

Module Contents

quimb.tensor.drawing.autocorrect_kwargs(func=None, valid_kwargs=None)[source]

A decorator that suggests the right keyword arguments if you get them wrong. Useful for functions with many specific options.

Parameters:
  • func (callable, optional) – The function to decorate.

  • valid_kwargs (sequence[str], optional) – The valid keyword arguments for func, if not given these are inferred from the function signature.

quimb.tensor.drawing.check_opt(name, value, valid)[source]

Check whether value takes one of valid options, and raise an informative error if not.

quimb.tensor.drawing.HAS_FA2
quimb.tensor.drawing.draw_tn(tn, color=None, *, show_inds=None, show_tags=None, output_inds=None, highlight_inds=(), highlight_tids=(), highlight_inds_color=(1.0, 0.2, 0.2), highlight_tids_color=(1.0, 0.2, 0.2), custom_colors=None, legend='auto', dim=2, fix=None, layout='auto', initial_layout='auto', refine_layout='auto', iterations='auto', k=None, pos=None, node_color=None, node_scale=1.0, node_size=None, node_alpha=1.0, node_shape='o', node_outline_size=None, node_outline_darkness=0.9, node_hatch='', edge_color=None, edge_scale=1.0, edge_alpha=1 / 2, multi_edge_spread=0.1, multi_tag_style='auto', show_left_inds=True, arrow_opts=None, label_color=None, font_size=10, font_size_inner=7, font_family='monospace', isdark=None, title=None, backend='matplotlib', figsize=(6, 6), margin=None, xlims=None, ylims=None, get=None, return_fig=False, ax=None)[source]

Plot this tensor network as a networkx graph using matplotlib, with edge width corresponding to bond dimension.

Parameters:
  • color (sequence of tags, optional) – If given, uniquely color any tensors which have each of the tags. If some tensors have more than of the tags, only one color will show.

  • output_inds (sequence of str, optional) – For hyper tensor networks explicitly specify which indices should be drawn as outer indices. If not set, the outer indices are assumed to be those that only appear on a single tensor.

  • highlight_inds (iterable, optional) – Highlight these edges.

  • highlight_tids (iterable, optional) – Highlight these nodes.

  • highlight_inds_color – What color to use for highlight_inds nodes.

  • highlight_tids_color (tuple[float], optional) – What color to use for highlight_tids nodes.

  • show_inds ({None, False, True, 'all', 'bond-size'}, optional) – Explicitly turn on labels for each tensors indices.

  • show_tags ({None, False, True}, optional) – Explicitly turn on labels for each tensors tags.

  • custom_colors (sequence of colors, optional) – Supply a custom sequence of colors to match the tags given in color.

  • title (str, optional) – Set a title for the axis.

  • legend ("auto" or bool, optional) – Whether to draw a legend for the colored tags. If "auto" then only draw a legend if there are less than 20 tags.

  • dim ({2, 2.5, 3}, optional) – What dimension to position the graph nodes in. 2.5 positions the nodes in 3D but then projects then down to 2D.

  • fix (dict[tags_ind_or_tid], (float, float)], optional) – Used to specify actual relative positions for each tensor node. Each key should be a sequence of tags that uniquely identifies a tensor, a tid, or a ind, and each value should be a (x, y) coordinate tuple.

  • layout (str, optional) –

    How to layout the graph. Can be any of the following:

    • 'auto': layout the graph using a networkx method then relax the layout using a force-directed algorithm.

    • a networkx layout method name, e.g. 'kamada_kawai': just layout the graph using a networkx method, with no relaxation.

    • a graphviz method such as 'dot', 'neato' or 'sfdp': layout the graph using pygraphviz.

  • initial_layout ({'auto', 'spectral', 'kamada_kawai', 'circular', ) – ‘planar’, ‘random’, ‘shell’, ‘bipartite’, …}, optional If layout == 'auto' The name of a networkx layout to use before iterating with the spring layout. Set layout directly or iterations=0 if you don’t want any spring relaxation.

  • iterations (int, optional) – How many iterations to perform when when finding the best layout using node repulsion. Ramp this up if the graph is drawing messily.

  • k (float, optional) – The optimal distance between nodes.

  • pos (dict, optional) – Pre-computed positions for the nodes. If given, this will override layout. The nodes shouuld be exactly the same as the nodes in the graph returned by draw(get='graph').

  • node_color (tuple[float], optional) – Default color of nodes.

  • node_scale (float, optional) – Scale the node sizes by this factor, in addition to the automatic scaling based on the number of tensors.

  • node_size (None, float or dict, optional) – How big to draw the tensors. Can be a global single value, or a dict containing values for specific tags or tids. This is in absolute figure units. See node_scale simply scale the node sizes up or down.

  • node_alpha (float, optional) – Transparency of the nodes.

  • node_shape (None, str or dict, optional) – What shape to draw the tensors. Should correspond to a matplotlib scatter marker. Can be a global single value, or a dict containing values for specific tags or tids.

  • node_outline_size (None, float or dict, optional) – The width of the border of each node. Can be a global single value, or a dict containing values for specific tags or tids.

  • node_outline_darkness (float, optional) – Darkening of nodes outlines.

  • edge_color (tuple[float], optional) – Default color of edges.

  • edge_scale (float, optional) – How much to scale the width of the edges.

  • edge_alpha (float, optional) – Set the alpha (opacity) of the drawn edges.

  • multi_edge_spread (float, optional) – How much to spread the lines of multi-edges.

  • show_left_inds (bool, optional) – Whether to show tensor.left_inds as incoming arrows.

  • arrow_closeness (float, optional) – How close to draw the arrow to its target.

  • arrow_length (float, optional) – The size of the arrow with respect to the edge.

  • arrow_overhang (float, optional) – Varies the arrowhead between a triangle (0.0) and ‘V’ (1.0).

  • arrow_linewidth (float, optional) – The width of the arrow line itself.

  • label_color (tuple[float], optional) – Color to draw labels with.

  • font_size (int, optional) – Font size for drawing tags and outer indices.

  • font_size_inner (int, optional) – Font size for drawing inner indices.

  • font_family (str, optional) – Font family to use for all labels.

  • isdark (bool, optional) – Explicitly specify that the background is dark, and use slightly different default drawing colors. If not specified detects automatically from matplotlib.rcParams.

  • figsize (tuple of int, optional) – The size of the drawing.

  • margin (None or float, optional) – Specify an argument for ax.margin, else the plot limits will try and be computed based on the node positions and node sizes.

  • xlims (None or tuple, optional) – Explicitly set the x plot range.

  • xlims – Explicitly set the y plot range.

  • get ({None, 'pos', 'graph'}, optional) –

    If None then plot as normal, else if:

    • 'pos', return the plotting positions of each tid and ind drawn as a node, this can supplied to subsequent calls as fix=pos to maintain positions, even as the graph structure changes.

    • 'graph', return the networkx.Graph object. Note that this will potentially have extra nodes representing output and hyper indices.

  • return_fig (bool, optional) – If True and ax is None then return the figure created rather than executing pyplot.show().

  • ax (matplotlib.Axis, optional) – Draw the graph on this axis rather than creating a new figure.

quimb.tensor.drawing.parse_dict_to_tids_or_inds(spec, tn, default='__NONE__')[source]

Parse a dictionary possibly containing a mix of tags, tids and inds, to a dictionary with only sinlge tids and inds as keys. If a tag or set of tags are given as a key, all matching tensor tids will receive the value.

quimb.tensor.drawing._add_legend_matplotlib(ax, colors, legend, node_outline_darkness, label_color, font_family)[source]
quimb.tensor.drawing._draw_matplotlib(edges, nodes, *, colors=None, node_outline_darkness=0.9, title=None, legend=True, multi_edge_spread=0.1, multi_tag_style='auto', arrow_opts=None, label_color=None, font_family='monospace', figsize=(6, 6), margin=None, xlims=None, ylims=None, return_fig=False, ax=None)[source]
quimb.tensor.drawing._linearize_graph_data(G, multi_tag_style='auto')[source]
quimb.tensor.drawing._draw_matplotlib3d(G, **kwargs)[source]
quimb.tensor.drawing._draw_plotly(G, **kwargs)[source]
quimb.tensor.drawing._normalize_positions(pos)[source]
quimb.tensor.drawing._rotate(xy, theta)[source]

Return a rotated set of points.

quimb.tensor.drawing._span(xy)[source]

Return the vertical span of the points.

quimb.tensor.drawing._massage_pos(pos, nangles=360, flatten=False)[source]

Rotate a position dict’s points to cover a small vertical span

quimb.tensor.drawing.phyllotaxis_points(n)[source]

J. Kogan, “A New Computationally Efficient Method for Spacing Points on a Sphere,” Rose-Hulman Undergraduate Mathematics Journal, 18(2), 2017 Article 5. scholar.rose-hulman.edu/rhumj/vol18/iss2/5.

quimb.tensor.drawing.layout_single_tensor(tn, dim=2)[source]

Manually layout indices around a tensor either in a circle or sphere.

quimb.tensor.drawing.layout_networkx(G, layout='kamada_kawai', pos0=None, fixed=None, dim=2, **kwargs)[source]
quimb.tensor.drawing.layout_pygraphviz(G, layout='neato', pos0=None, fixed=None, dim=2, iterations=None, k=None, **kwargs)[source]
quimb.tensor.drawing.get_positions(tn, G, *, dim=2, fix=None, layout='auto', initial_layout='auto', refine_layout='auto', iterations='auto', k=None)[source]
quimb.tensor.drawing.get_colors(color, custom_colors=None, alpha=None)[source]

Generate a sequence of rgbs for tag(s) color.

quimb.tensor.drawing.to_rgba_str(color, alpha=None)[source]
quimb.tensor.drawing.auto_color_html(s)[source]

Automatically hash and color a string for HTML display.

quimb.tensor.drawing.visualize_tensor(tensor, **kwargs)[source]

Visualize all entries of a tensor, with indices mapped into the plane and values mapped into a color wheel.

Parameters:
  • tensor (Tensor) – The tensor to visualize.

  • skew_factor (float, optional) – When there are more than two dimensions, a factor to scale the rotations by to avoid overlapping data points.

  • size_map (bool, optional) – Whether to map the tensor value magnitudes to marker size.

  • size_scale (float, optional) – An overall factor to scale the marker size by.

  • alpha_map (bool, optional) – Whether to map the tensor value magnitudes to marker alpha.

  • alpha_pow (float, optional) – The power to raise the magnitude to when mapping to alpha.

  • alpha (float, optional) – The overall alpha to use for all markers if not alpha_map.

  • show_lattice (bool, optional) – Show a small grey dot for every ‘lattice’ point regardless of value.

  • lattice_opts (dict, optional) – Options to pass to maplotlib.Axis.scatter for the lattice points.

  • linewidths (float, optional) – The linewidth to use for the markers.

  • marker (str, optional) – The marker to use for the markers.

  • figsize (tuple, optional) – The size of the figure to create, if ax is not provided.

  • ax (matplotlib.Axis, optional) – The axis to draw to. If not provided, a new figure will be created.

Returns:

  • fig (matplotlib.Figure) – The figure containing the plot, or None if ax was provided.

  • ax (matplotlib.Axis) – The axis containing the plot.

quimb.tensor.drawing.choose_squarest_grid(x)[source]
quimb.tensor.drawing.visualize_tensors(tn, mode='network', r=None, r_scale=1.0, figsize=None, **visualize_opts)[source]

Visualize all the entries of every tensor in this network.

Parameters:
  • tn (TensorNetwork) – The tensor network to visualize.

  • mode ({'network', 'grid', 'row', 'col'}, optional) –

    How to arrange each tensor’s visualization.

    • 'network': arrange each tensor’s visualization according to the

      automatic layout given by draw.

    • 'grid': arrange each tensor’s visualization in a grid.

    • 'row': arrange each tensor’s visualization horizontally.

    • 'col': arrange each tensor’s visualization vertically.

  • r (float, optional) – The absolute radius of each tensor’s visualization, when mode='network'.

  • r_scale (float, optional) – A relative scaling factor for the radius of each tensor’s visualization, when mode='network'.

  • figsize (tuple, optional) – The size of the figure to create, if ax is not provided.

  • visualize_opts – Supplied to visualize_tensor.