utopya.eval.plots package

Contents

utopya.eval.plots package#

The plot_funcs subpackage supplies general plotting functions.

These can be used via the plotting framework and its ExternalPlotCreator, of which this subpackage is the base package to use for relative module imports.

It extends those capabilities provided by the dantro plotting framework.

Submodules#

utopya.eval.plots._attractor module#

This module holds data processing functionality that is used in the plot functions.

utopya.eval.plots._attractor.find_endpoint(data: DataArray, *, time: int = -1, **kwargs) Tuple[bool, DataArray][source]#

Find the endpoint of a dataset wrt. time coordinate.

This function is compatible with the utopya.eval.plots.attractor.bifurcation_diagram().

Parameters:
Returns:

The result in the form of a 2-tuple

(endpoint found, endpoint)

Return type:

Tuple[bool, xarray.DataArray]

utopya.eval.plots._attractor.find_fixpoint(data: Dataset, *, spin_up_time: int = 0, abs_std: Optional[float] = None, rel_std: Optional[float] = None, mean_kwargs=None, std_kwargs=None, isclose_kwargs=None, squeeze: bool = True) Tuple[bool, float][source]#

Find the fixpoint(s) of a dataset and confirm it by standard deviation. For dimensions that are not time the fixpoints are compared and duplicates removed.

This function is compatible with the utopya.eval.plots.attractor.bifurcation_diagram().

Parameters:
  • data (xarray.Dataset) – The data

  • spin_up_time (int, optional) – The first timestep included

  • abs_std (float, optional) – The maximal allowed absolute standard deviation

  • rel_std (float, optional) – The maximal allowed relative standard deviation

  • mean_kwargs (dict, optional) – Additional keyword arguments passed on to the appropriate array function for calculating mean on data.

  • std_kwargs (dict, optional) – Additional keyword arguments passed on to the appropriate array function for calculating std on data.

  • isclose_kwargs (dict, optional) – Additional keyword arguments passed on to the appropriate array function for calculating np.isclose for fixpoint-duplicates across dimensions other than ‘time’.

  • squeeze (bool, optional) – Use the data.squeeze method to remove dimensions of length one. Default is True.

Returns:

(fixpoint found, mean)

Return type:

tuple

utopya.eval.plots._attractor.find_multistability(*args, **kwargs) Tuple[bool, float][source]#

Find the multistabilities of a dataset.

Invokes find_fixpoint(). This function is conclusive if find_fixpoint() is conclusive with multiple entries.

Parameters:
Returns

Tuple[bool, float]: (multistability found, mean value)

utopya.eval.plots._attractor.find_oscillation(data: Dataset, *, spin_up_time: int = 0, squeeze: bool = True, **find_peak_kwargs) Tuple[bool, list][source]#

Find oscillations in a dataset.

This function is compatible with the utopya.eval.plots.attractor.bifurcation_diagram().

Parameters:
  • data (xarray.Dataset) – The data

  • spin_up_time (int, optional) – The first timestep included

  • squeeze (bool, optional) – Use the data.squeeze method to remove dimensions of length one. Default is True.

  • **find_peak_kwargs – Passed on to scipy.signal.find_peaks(). If not given, will set height kwarg to -1.e+15.

Returns:

(oscillation found, [min, max])

Return type:

Tuple[bool, list]

utopya.eval.plots._graph module#

This module provides the GraphPlot class.

utopya.eval.plots._graph.POSITIONING_MODELS_NETWORKX = {'bipartite': <function bipartite_layout>, 'circular': <function circular_layout>, 'graphviz': <function graphviz_layout>, 'kamada_kawai': <function kamada_kawai_layout>, 'planar': <function planar_layout>, 'random': <function random_layout>, 'shell': <function shell_layout>, 'spectral': <function spectral_layout>, 'spiral': <function spiral_layout>, 'spring': <function spring_layout>}#

Available networkx node layout options

class utopya.eval.plots._graph.GraphPlot(g: Graph, *, fig: matplotlib.figure.Figure = None, ax: matplotlib.axes.Axes = None, select: dict = None, positions: dict = None, nodes: dict = None, edges: dict = None, node_labels: dict = None, edge_labels: dict = None, mark_nodes: dict = None, mark_edges: dict = None)[source]#

Bases: object

This class provides an interface for visualizing a :py:class`networkx.Graph` object or a graph created from a GraphGroup.

__init__(g: Graph, *, fig: matplotlib.figure.Figure = None, ax: matplotlib.axes.Axes = None, select: dict = None, positions: dict = None, nodes: dict = None, edges: dict = None, node_labels: dict = None, edge_labels: dict = None, mark_nodes: dict = None, mark_edges: dict = None)[source]#

Initializes a GraphPlot, which provides drawing utilities for a fixed graph.

The drawing kwargs are stored and used when calling draw().

A GraphPlot can also be initialized from a GraphGroup via the from_group() classmethod.

If drawing multiple times from the same GraphPlot instance, be aware that it only keeps track of the nodes/edges/labels/colorbars that were last associated with it. Use clear_plot() before re-drawing on the same axis.

Note

For some graph drawing kwargs it is possible to configure an automatized mapping from node/edge properties. This property mapping has the following syntax:

some_layout_property:
  from_property: my_node_or_edge_property
  scale_to_interval: [low_lim, up_lim]

The from_property specifies the node or edge property to be mapped from. If scale_to_interval is given, the layout property values are rescaled linearly the specified interval.

Parameters:
  • g (networkx.Graph) – The networkx graph object

  • fig (matplotlib.figure.Figure, optional) – The matplotlib figure used for drawing

  • ax (matplotlib.axes.Axes, optional) – The matplotlib axes used for drawing

  • select (dict, optional) –

    Draw only a subgraph induced by a selection of nodes. Either select a list of nodes by passing the nodelist argument or do a radial node selection by specifying a center node and the radius. The following arguments can be passed additionally:

    open_edges (bool, optional):

    Whether to draw the edges for which only one of source and destination is in the set of selected nodes. Disabled by default.

    drop (bool, optional):

    Whether to remove the non-selected nodes from the graph. If False, all nodes are passed to the node positioning model. Enabled by default.

  • positions (dict, optional) –

    Configuration for the node positioning. The following arguments are available:

    from_dict (dict, optional):

    Node positions (2-tuples) keyed by node. If given, the layouting algorithm given by the model argument will be ignored.

    model (Union[str, Callable], optional):

    The layout model that is used to calculate the node positions (default=``spring``). Available networkx layout models are: spring, circular, shell, bipartite, kamada_kawai, planar, random, spectral, spiral. See POSITIONING_MODELS_NETWORKX.

    If installed, GraphViz models can be selected using the agraph_graphviz graphviz_layout()) layout function, with the prog argument specifying the layout model. Options depend on the GraphViz version but may include: dot, neato, fdp, sfdp, twopi, circo. Other arguments must be passed as a single string separated by a hyphen, e.g. '-len=1000-overlap_scaling=100-sep=100'.

    If the argument is a callable, it is invoked with the graph as the first positional argument and is expected to return networkx-compatible node positions, i.e. a mapping from nodes to a 2-tuple denoting the position.

    further kwargs:

    Passed on to the chosen layout model.

  • nodes (dict, optional) –

    Drawing configuration for the nodes. The following arguments are available for property mapping: node_size, node_color, alpha. The following arguments are allowed:

    node_size (scalar or sequence of scalars, optional):

    The node size (default=300). Available for property mapping. Can be mapped directly from the nodes’ degree, in_degree, or out_degree by setting the from_property argument accordingly.

    node_color (color or sequene of colors, optional):

    Single color (string or RGB(A) tuple or numeric value) or sequence of colors (default: ‘#1f78b4’). If numeric values are specified they will be mapped to colors using the cmap and vmin, vmax parameters.

    If mapped from property it may contain an additional map_to_scalar, which is a dict of numeric target values keyed by property value. This allows to map from non-numeric (e.g. categorical) properties.

    cmap (optional):

    The colormap. Passed as cmap to ColorManager.

    cmap_norm (optional):

    The norm used for the color mapping. Passed as norm to ColorManager. Is overwritten, if a discrete colormap is specified in cmap.

    colorbar (dict, optional):

    The node colorbar configuration. The following arguments are allowed:

    enabled (bool, optional):

    Whether to plot a colorbar. Enabled by default if node_color is mapped from property.

    labels (dict, optional):

    Colorbar tick-labels keyed by tick position (see create_cbar()).

    tick_params (dict, optional):

    Colorbar axis tick parameters

    label (str, optional):

    The axis label for the colorbar

    label_kwargs (dict, optional):

    Further keyword arguments to adjust the aesthetics of the colorbar label

    further kwargs:

    Passed on to create_cbar().

    further kwargs:

    Passed to draw_networkx_nodes when calling draw().

  • edges (dict, optional) –

    Drawing configuration for the edges. The following arguments are available for property mapping: edge_color, width.

    The edge_color, edge_cmap, and colorbar arguments behave analogously for the edges as nodes.node_color, nodes.cmap, and nodes.colorbar for the nodes. Any further kwargs are (after applying property mapping), passed on to draw_networkx_edges when calling draw().

    If arrows are to be drawn (i.e. for directed edges with arrows=True), only norms of type matplotlib.colors.Normalize are allowed.

  • node_labels (dict, optional) –

    Drawing configuration for the node labels. The following arguments are allowed:

    enabled (bool, optional):

    Whether to draw node labels. Disabled by default. If enabled, nodes are labeled by their index by default.

    show_only (list, optional):

    If given, labels are drawn only for the nodes in this list.

    labels (dict, optional):

    Custom text labels keyed by node. Available for property mapping.

    format (str, optional):

    If labels are mapped from property this format string containing a label key is used for all node labels.

    decode (str, optional):

    Decoding specifier which is applied to all property values if format is used.

    further kwargs:

    Passed on to draw_networkx_labels when calling draw().

  • edge_labels (dict, optional) –

    Drawing configuration for the edge labels. The following arguments are allowed:

    enabled (bool, optional):

    Whether to draw edge labels. Disabled by default. If enabled, edges are labeled by their (source, destination) pair by default.

    show_only (list, optional):

    If given, labels are drawn only for the edges (2-tuples) in this list.

    edge_labels (dict, optional):

    Custom text labels keyed by edge (2-tuple). Available for property mapping.

    format (str, optional):

    If edge_labels are mapped from property this format string containing a label key is used for all edge labels.

    decode (str, optional):

    Decoding specifier which is applied to all property values if format is used.

    further kwargs:

    Passed on to draw_networkx_edge_labels when calling draw().

  • mark_nodes (dict, optional) – Mark specific nodes by changing their edgecolor. Either specify a color for a list of nodes (nodelist), or specify a colors dictionary of colors keyed by node. Updates an existing nodes.edgecolors entry.

  • mark_edges (dict, optional) – Mark specific edges by changing their color. Either specify a color for a list of edges (edgelist), or specify a colors dictionary of colors keyed by edge (2-tuple). Updates an existing edges.edge_color entry.

property g#

Get a deep copy of the graph associated with this instance.

Returns:

The graph object

Return type:

networkx.Graph

draw(*, fig: matplotlib.figure.Figure = None, ax: matplotlib.axes.Axes = None, positions: dict = None, nodes: dict = None, edges: dict = None, node_labels: dict = None, edge_labels: dict = None, mark_nodes: dict = None, mark_edges: dict = None, suppress_cbar: bool = False, update_colormapping: bool = True, **add_colorbars)[source]#

Draws the graph associated with the GraphPlot using the current drawing configuration.

The current drawing configuration may be temporarily updated for this plot. The respective arguments accept the same input as in __init__().

Parameters:
  • fig (matplotlib.figure.Figure, optional) – matplotlib figure

  • ax (matplotlib.axes.Axes, optional) – matplotlib axis

  • positions (dict, optional) – Position configuration. If given, the current positions are replaced. If using a node positioning model the positions are recalculated.

  • nodes (dict, optional) – Temporarily updates the node-kwargs

  • edges (dict, optional) – Temporarily updates the edge-kwargs

  • node_labels (dict, optional) – Temporarily updates the node-label-kwargs

  • edge_labels (dict, optional) – Temporarily updates the edge-label-kwargs

  • mark_nodes (dict, optional) – Temporarily mark nodes kwargs

  • mark_edges (dict, optional) – Temporarily mark edges kwargs

  • suppress_cbar (bool, optional) – Whether to suppress the drawing of colorbars

  • update_colormapping (bool, optional) – Whether to reconfigure the nodes’ and edges’ ColorManager (default=True). If True, the respective configuration entries are ignored. Set to False if doing repetitive plotting with fixed colormapping.

  • **add_colorbars – Passed to add_colorbars()

add_colorbars(*, show_node_cbar=True, show_edge_cbar=True, fig=None, ax=None, remove_previous=True, **update_cbar_kwargs)[source]#

Adds colorbars for the drawn nodes and edges.

Parameters:
  • show_node_cbar (bool, optional) – Whether to create a colorbar for the nodes

  • show_edge_cbar (bool, optional) – Whether to create a colorbar for the edges

  • fig (None, optional) – matplotlib figure

  • ax (None, optional) – matplotlib axis

  • remove_previous (bool, optional) – Whether the colorbars which are currently associated with the GraphPlot are removed. If False, the GraphPlot still loses track of the colorbars, they can not be removed via the GraphPlot afterwards.

  • **update_cbar_kwargs – Update both node and edge colorbar kwargs, passed to create_cbar().

clear_plot(*, keep_colorbars: bool = False)[source]#

Removes all matplotlib objects associated with the GraphPlot from the respective axis. The GraphPlot loses track of all those objects, the respective class attributes are reset.

Parameters:

keep_colorbars (bool, optional) – Whether to keep the node and edge colorbars. If True, the GraphPlot still loses track of the colorbars, they can not be removed via the GraphPlot afterwards.

classmethod from_group(graph_group: utopya.eval.groups.GraphGroup, *, graph_creation: dict = None, register_property_maps: dict = None, clear_existing_property_maps: bool = True, **init_kwargs)[source]#

Initializes a GraphPlot from a GraphGroup.

Parameters:
  • graph_group (utopya.eval.groups.GraphGroup) – The graph group

  • graph_creation (dict, optional) – Configuration of the graph creation. Passed to create_graph_from_group()

  • register_property_maps (dict, optional) – Properties to be registered in the graph group before the graph creation keyed by name

  • clear_existing_property_maps (bool, optional) – Whether to clear any existing property maps from the graph group

  • **init_kwargs – Passed to __init__()

static create_graph_from_group(graph_group: utopya.eval.groups.GraphGroup, *, register_property_maps: dict = None, clear_existing_property_maps: bool = True, **graph_creation) Graph[source]#

Creates a networkx.Graph from a :py:class`utopya.eval.groups.GraphGroup`. Additional property maps may be added to the group beforehand.

Parameters:
  • graph_group (utopya.eval.groups.GraphGroup) – The group to create the graph from

  • register_property_maps (dict, optional) – Properties to be registered in the graph group before the graph creation keyed by name.

  • clear_existing_property_maps (bool, optional) – Whether to clear any existing property maps from the graph group.

  • **graph_creation – Configuration of the graph creation. Passed on to the create_graph method implemented in dantro, create_graph().

Returns:

The created graph object.

Return type:

networkx.Graph

parse_positions(*, from_dict: Optional[Dict[Any, Tuple[float, float]]] = None, model: Optional[Union[Callable, str]] = None, **kwargs)[source]#

Parses the node positioning configuration. If a node positioning model is to be used, (re)calculates the positions.

Parameters:
  • from_dict (dict, optional) – Explicit node positions (2-tuples keyed by node). If given, the model argument will be ignored.

  • model (Union[str, Callable], optional) – The model used for node positioning. If it is a string, it is looked up from the available networkx positioning models. If None, the spring model is used. If it is callable, it will be called with the graph as first positional argument.

  • **kwargs – Passed to the node positioning routine

Raises:

ModuleNotFoundError – If a graphviz model was chosen but pygraphviz was not importable (via networkx).

parse_nodes(*, node_size=None, node_color=None, alpha=None, cmap=None, cmap_norm=None, vmin: Optional[float] = None, vmax: Optional[float] = None, edgecolors=None, colorbar: Optional[dict] = None, update_colormapping: bool = True, **kwargs)[source]#

Parses the node layout configuration and updates the node kwargs of the GraphPlot.

The following arguments are available for property mapping: node_size, node_color, alpha.

Parameters:
  • node_size (None, optional) – Size of nodes (default=300). Available for property mapping. Can be mapped directly from the nodes’ degree, in_degree, or out_degree by setting the from_property argument accordingly.

  • node_color (None, optional) –

    Single color (string or RGB(A) tuple or numeric value) or sequence of colors. If numeric values are specified they will be mapped to colors using the cmap and vmin, vmax parameters.

    If mapped from property it may contain an additional map_to_scalar, which is a dict of numeric target values keyed by property value. This allows to map from non-numeric (e.g. categorical) properties.

  • alpha (None, optional) – The node transparency

  • cmap (None, optional) – The colormap. Passed as cmap to ColorManager.

  • cmap_norm (None, optional) – The norm used for the color mapping. Passed as norm to ColorManager. Is overwritten, if a discrete colormap is specified in cmap.

  • vmin (float, optional) – Minimum for the colormap scaling

  • vmax (float, optional) – Maximum for the colormap scaling

  • edgecolors (optional) – Colors of node borders. The default is ‘none’, i.e. no node border is drawn.

  • colorbar (dict, optional) –

    The node colorbar configuration. The following keys are available:

    enabled (bool, optional):

    Whether to plot a colorbar. Enabled by default if node_color is mapped from property.

    labels (dict, optional):

    Colorbar tick-labels keyed by tick position (see ColorManager).

    further kwargs: Passed on to

    create_cbar()

  • update_colormapping (bool, optional) – Whether to reconfigure the nodes’ ColorManager (default: True). If False, the respective arguments are ignored. Set to False if doing repetitive plotting with fixed colormapping.

  • **kwargs – Update the node kwargs. Passed to draw_networkx_nodes() when calling draw()

parse_edges(*, width=None, edge_color=None, edge_cmap=None, cmap_norm=None, alpha=None, edge_vmin: Optional[float] = None, edge_vmax: Optional[float] = None, colorbar: Optional[dict] = None, update_colormapping: bool = True, **kwargs)[source]#

Parses the edge layout configuration and updates the edge kwargs of the GraphPlot.

The following arguments are available for property mapping: width, edge_color.

Parameters:
  • width (None, optional) – Line width of edges

  • edge_color (None, optional) –

    Single color (string or RGB(A) tuple or numeric value) or sequence of colors (default=’k’). If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin, edge_vmax parameters.

    If mapped from property it may contain an additional map_to_scalar, which is a dict of numeric target values keyed by property value. This allows to map from non-numeric (e.g. categorical) properties.

  • edge_cmap (None, optional) – The colormap. Passed as cmap to ColorManager.

  • cmap_norm (None, optional) – The norm used for the color mapping. Passed as norm to ColorManager. Is overwritten, if a discrete colormap is specified in edge_cmap. If arrows are to be drawn (i.e. for directed edges with arrows=True), only norms of type matplotlib.colors.Normalize are allowed.

  • edge_vmin (float, optional) – Minimum for the colormap scaling

  • edge_vmax (float, optional) – Maximum for the colormap scaling

  • colorbar (dict, optional) –

    The edge colorbar configuration. The following keys are available:

    enabled (bool, optional):

    Whether to plot a colorbar. Enabled by default if edge_color is mapped from property.

    labels (dict, optional):

    Colorbar tick-labels keyed by tick position (see ColorManager).

    further kwargs: Passed on to

    create_cbar()

  • update_colormapping (bool, optional) – Whether to reconfigure the edges’ ColorManager (default=True). If False, the respective arguments are ignored. Set to False if doing repetitive plotting with fixed colormapping.

  • **kwargs – Update the edge kwargs. Passed to draw_networkx_nodes() when calling draw().

Raises:

TypeError – On norm type other than matplotlib.colors.Normalize and if arrows are to be drawn.

parse_node_labels(*, enabled: bool = False, show_only: Optional[list] = None, labels: Optional[dict] = None, format: str = '{label}', decode: Optional[str] = None, **kwargs)[source]#

Parses the node labels configuration and updates the node label kwargs of the GraphPlot.

Parameters:
  • enabled (bool, optional) – Whether to draw node labels.

  • show_only (list, optional) – If given, labels are drawn only for the nodes in this list

  • labels (dict, optional) – Custom text labels keyed by node. Available for property mapping.

  • format (str, optional) – If labels are mapped from property this format string containing a label key is used for all node labels.

  • decode (str, optional) – Decoding specifier which is applied to all property values if format is used.

  • **kwargs – Update the node label kwargs. Passed to nx.draw_networkx_labels when calling draw().

parse_edge_labels(*, enabled: bool = False, show_only: Optional[list] = None, edge_labels: Optional[dict] = None, format: str = '{label}', decode: Optional[str] = None, **kwargs)[source]#

Parses the edge labels configuration and updates the edge label kwargs of the GraphPlot.

Parameters:
  • enabled (bool, optional) – Whether to draw edge labels.

  • show_only (list, optional) – If given, labels are drawn only for the edges (2-tuples) in this list

  • edge_labels (dict, optional) – Custom text labels keyed by edge (2-tuple). Available for property mapping.

  • format (str, optional) – If edge_labels are mapped from property this format string containing a label key is used for all edge labels.

  • decode (str, optional) – Decoding specifier which is applied to all property values if format is used.

  • **kwargs – Update the edge label kwargs. Passed to nx.draw_networkx_edge_labels when calling draw().

mark_nodes(*, nodelist: Optional[list] = None, color=None, colors: Optional[dict] = None)[source]#

Mark specific nodes by changing their edgecolor.

Note

This function overwrites the edgecolors entry in the node kwargs. Thus it might overwrite an existing edgecolors entry specified via parse_nodes() (and vice versa).

Parameters:
  • nodelist (list, optional) – Nodes to mark with the color specified via color

  • color (None, optional) – Single edgecolor to use for the nodes in nodelist

  • colors (dict, optional) – Edgecolors keyed by node to mark. Must be None if nodelist is given.

Raises:

ValueError – On ambiguous or missing mark_nodes configuration

mark_edges(*, edgelist: Optional[list] = None, color=None, colors: Optional[dict] = None)[source]#

Mark specific edges by changing their color.

Note

This function overwrites the edge_color entry in the edge kwargs. Thus it might overwrite an existing edge_color entry specified via parse_edges() (and vice versa).

Parameters:
  • edgelist (list, optional) – Edges to mark with the color specified via color

  • color (None, optional) – Single color to use for the edges in edgelist

  • colors (dict, optional) – Colors keyed by edge (2-tuple) to mark. Must be None if edgelist is given.

Raises:

ValueError – On ambiguous or missing mark_edges configuration

_configure_node_patch_sizes()[source]#

In the edge drawing kwargs adjusts the node patch specifications ensuring that, in the case of a directed graph, the arrows end exactly at the node boundaries. Besides the node_size also accounts for node boundaries.

static _scale_to_interval(data: list, interval=None) list[source]#

Rescales the data linearly to the given interval. If no interval is given the data is returned as it is.

Parameters:
  • data (list) – data that is rescaled linearly to the given interval

  • interval (optional) – The target interval

Returns:

rescaled data

Return type:

list

Raises:

ValueError – On invalid interval specification

_select_subgraph(nodelist: Optional[list] = None, drop: bool = True, **kwargs)[source]#

Select a subgraph to draw. Sets the lists of nodes and edges to draw and the nodes to shrink. Either a list of nodes is selected or radial selection is done.

Parameters:
  • nodelist (list, optional) – If given, select nodes from list

  • drop (bool, optional) – Whether to remove the non-selected nodes and edges from the graph

  • **kwargs – Passed to the selection routine

utopya.eval.plots._mpl module#

This module provides matplotlib-related helper constructs

utopya.eval.plots._mpl.adjust_figsize_to_aspect(aspect: float, *, fig: matplotlib.figure.Figure) Tuple[float, float][source]#

Adjusts the given figures size, enlarging it to match the given aspect ratio where width = height * aspect.

Parameters:
Returns:

New width and height of the figure in inches.

Return type:

Tuple[float, float]

class utopya.eval.plots._mpl.HandlerEllipse(*args, **kwargs)[source]#

Bases: HandlerPatch

Custom legend handler to turn an ellipse handle into a legend key.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source]#

Create an ellipse as a matplotlib artist object.

utopya.eval.plots._utils module#

Utility functions that assist plot functions

utopya.eval.plots._utils.calc_pxmap_rectangles(*, x_coords: ndarray, y_coords: ndarray, x_scale: str = 'lin', y_scale: str = 'lin', default_pos: Tuple[float, float] = (0.0, 0.0), default_distance: float = 1.0, size_factor: float = 1.0, extend: bool = False) Tuple[Dataset, Dict[str, tuple]][source]#

Calculates the positions and sizes of rectangles centered at the given coordinates in such a way that they fully cover the 2D space spanned by the coordinates.

The exact values of the coordinates are arbitrary, but they should be ordered. The resulting rectangles will not necessarily be centered around the coordinate, but the distance between rectangle edges is set such that it lies halfway to the next coordinate in that dimension; the “halfway” is evaluated according to a certain scale.

Parameters:
  • x_coords (numpy.ndarray) – The x coordinates

  • y_coords (numpy.ndarray) – The y coordinates

  • x_scale (str, optional) – The x-axis scale, used to determine rectangle sizes.

  • y_scale (str, optional) – The y-axis scale, used to determine rectangle sizes.

  • default_pos (Tuple[float, float], optional) – If any of the coordinates is not given, this information will be used for creating the rectangle specification.

  • default_distance (float, optional) – If any of the coordinates is not given or of size 1, this distance to the next data point is assumed in that dimension. In such a case, the scale does not have an effect on the resulting rectangle.

  • size_factor (float, optional) – Scaling factor for the rectangle sizes

  • extend (bool, optional) – Whether to extend the rectangles of the points at the border of the domain such that the coordinate is _not_ at the edge of the rectangle but in the bulk.

Returns:

The first tuple element is the

dataset of rectangle specifications, each available as a data variable:

  • pos_x, pos_y: position of the lower-value coordinate of the rectangle. Together, this specifies the bottom left- hand corner of the rectangle (in a right-hand coordinate system)

  • len_x, len_y: lengths of the rectangle sides in the specified dimensions. Adding both these to the position leads to the top-right hand corner of the rectangle

  • rect_spec: A matplotlib-compatible rectangle specification, i.e. (position, width, height)

The second tuple element are the limits in x and y direction, given as dict with keys x and y.

Return type:

Tuple[xarray.Dataset, Dict[str, tuple]]

utopya.eval.plots.abm module#

Implements plot functions for agent-based models, e.g. of agents and their movement in a domain.

utopya.eval.plots.abm.MARKERS: Dict[str, Path] = {'fish': Path(array([[-5. ,  0. ],        [-2. ,  0.2],        [ 3. ,  2. ],        [ 3. ,  0. ],        [ 3. , -2. ],        [-2. , -0.2],        [-5. ,  0. ]]), array([1, 4, 4, 4, 4, 4, 4], dtype=uint8)), 'fish2': Path(array([[-5. ,  0. ],        [-2. ,  0.2],        [ 3. ,  2.5],        [ 3. ,  0. ],        [ 3. , -2.5],        [-2. , -0.2],        [-5. ,  0. ],        [-3. ,  0. ],        [-5.5, -1.5],        [-5. ,  0. ],        [-5.5,  1.5],        [ 2. ,  0. ],        [-2. , -1.3],        [-1. ,  0. ],        [-2. ,  1.3]]), array([1, 4, 4, 4, 4, 4, 4, 1, 2, 2, 2, 1, 2, 2, 2], dtype=uint8)), 'wedge': Path(array([[ 0. , -0.1],        [ 0.3,  0. ],        [ 0. ,  0.1],        [ 0. ,  0. ]]), array([ 1,  2,  2, 79], dtype=uint8))}#

Custom markers that can be used in AgentCollection, an essential part of abmplot().

Available markers:

  • wedge: A triangle that can be used to denote orientations.

  • fish: A simple fish-like shape.

  • fish2: A more elaborate fish-like shape.

../_images/markers.pdf

Hint

To have consistent orientations, note that markers should point along the positive x-axis. With increasing orientation values, they are rotated in counter-clockwise direction. Angles are measured in radians.

Note

Suggestions for additional markers are welcome.

class utopya.eval.plots.abm.AgentCollection(xy: Union[ndarray, Sequence[Union[Path, Tuple[float, float]]]], *, marker: Union[Path, Patch, str, dict] = 'auto', default_marker: Union[Path, Patch, str, dict] = 'o', default_marker_oriented: Union[Path, Patch, str, dict] = 'wedge', sizes: Optional[Union[float, Sequence[float]]] = None, size_scale: float = 1.0, normalize_marker_sizes: bool = True, orientations: Optional[Union[float, Sequence[float]]] = None, base_orientation: float = 0.0, tail_length: int = 0, tail_kwargs: Optional[dict] = None, tail_decay: float = 0.0, tail_max_segment_length: Optional[float] = None, use_separate_paths: bool = True, **kwargs)[source]#

Bases: PathCollection

A collection of agent markers and (optionally) their position history in the form of a tail. Combines PathCollection with a LineCollection for the tails.

__init__(xy: Union[ndarray, Sequence[Union[Path, Tuple[float, float]]]], *, marker: Union[Path, Patch, str, dict] = 'auto', default_marker: Union[Path, Patch, str, dict] = 'o', default_marker_oriented: Union[Path, Patch, str, dict] = 'wedge', sizes: Optional[Union[float, Sequence[float]]] = None, size_scale: float = 1.0, normalize_marker_sizes: bool = True, orientations: Optional[Union[float, Sequence[float]]] = None, base_orientation: float = 0.0, tail_length: int = 0, tail_kwargs: Optional[dict] = None, tail_decay: float = 0.0, tail_max_segment_length: Optional[float] = None, use_separate_paths: bool = True, **kwargs)[source]#

Set up an AgentCollection, visualizing agents and (optionally) their position history using a tail.

Hint

If you need a higher performance for this plot, consider not using the decaying tails, for which the line segments need to be drawn individually.

Parameters:
  • xy (Sequence[Tuple[float, float]]) – The positions of the agents. The number of agents is extracted from the length of this sequence or (x, y) positions or (N, 2) array.

  • marker (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict], optional) –

    The marker to use to denote agent positions. The following input types are possible:

    • A Path is used as it is

    • A dict is used as keyword arguments to the Path, where vertices can be a sequence of 2-tuples that defines the vertices of the path.

    • A Patch already defines a path, which is extracted and used as marker. All other properties are ignored.

    • str is looked up in MARKERS; if no such entry is available, the remaining options are evaluated.

    • All other input is used to construct a MarkerStyle from which the path is extracted.

  • default_marker (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict], optional) – The marker to use in case that marker is None and agents are not initialized with an orientation.

  • default_marker_oriented (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, dict], optional) – The marker to use in case that marker is None and agents are initialized with an orientation.

  • sizes (Union[float, Sequence[float]], optional) – Agent sizes in units of area (of bounding box) squared. If a scalar value is given, all agents will have the same size.

  • size_scale (float, optional) – A scaling factor for the sizes.

  • normalize_marker_sizes (bool, optional) – If True, will normalize the size of the given marker. This is done by computing the area of the bounding box and scaling the path such that the bounding box has an area of one.

  • orientations (Union[float, Sequence[float]], optional) – Single or individual orientations of the agents. Zero corresponds to pointing along the positive x-axis, with increasing orientation values leading to a counter-clockwise rotation. Angles need to be given in radians.

  • base_orientation (float, optional) – Rotates the given marker by this value such that all orientations have a constant offset.

  • tail_length (int, optional) – For non-zero integers, will draw a tail behind the agents that traces their position history. This is only relevant if the collection is used as part of an animation where the position history can be aggregated upon each call to set_offsets().

  • tail_kwargs (dict, optional) – Keyword arguments that are passed to the LineCollection which is used to represent the tails.

  • tail_decay (float, optional) – A decay factor. If non-zero, will multiply each consecutive tail segments alpha value with (1 - tail_decay).

  • tail_max_segment_length (float, optional) – If set, will not draw tail segments that are longer than this value in either the x- or the y-direction. This can be useful if agents move in a periodic space where positions may jump.

  • use_separate_paths (bool, optional) –

    If False, only a single path is used to represent all agents in the underlying PathCollection.

    Warning

    Setting this to False should only be done if all agents can be thought of as identical, i.e. have the same size, color, marker, and orientation — otherwise this leads to subtle and seemingly random breakage in the form of markers not being drawn.

  • **kwargs – Passed on to PathCollection

__len__() int[source]#

Number of agents associated with this AgentCollection

property has_orientation: bool#

Whether agent orientation is represented

property has_markers: bool#

Whether a marker will be shown; if disabled, can skip setting array data and thus increase performance somewhat …

property tail_length: int#

Length of the tail of each agent, i.e. the number of historic offset positions that are connected into a line.

property tails: Optional[LineCollection]#

The LineCollection that represents the tails of the agents — or None if tails are not activated.

Note

This collection still needs to be registered once with the axes via add_collection().

property markerpath: Optional[Path]#

Returns the used markerpath

draw_tails(**kwargs) LineCollection[source]#

Draws the tails from scratch, removing the currently added collection if there is one.

Note

If calling this, the collection representing the tails needs to be re-added to the desired axes. To update tail positions according to the offsets history, use update_tails().

update_tails() LineCollection[source]#

Updates the collection that holds the tails using the offsets history.

set_markersizes(sizes)[source]#

Sets the marker sizes, taking into account the size scaling.

Note

This behaves differently from the inherited set_sizes method and thus has a different name. The difference is that set_sizes() is also called during saving of a plot and would thus lead to repeated application of the size scaling, which is not desired.

set_offsets(offsets) None[source]#

Sets the offsets, i.e. path positions of all agents.

Invokes set_offsets() and afterwards stores the offset history, using it for update_tails().

set_orientations(orientations: Union[float, Sequence[float]]) None[source]#

Set the orientations of all agents. If a scalar is given, will set all orientations to that value. If any kind of sequence is given, will associate individual orientations with agents.

Note

This can only be used if the collection was initialized with orientations, see __init__().

get_orientations() Sequence[float][source]#

Returns the current orientations of all agents.

Note

Changing the returned object does not rotate the agents! Use set_orientations() to achieve that.

_prepare_marker_path(marker: Union[Path, Patch, str, list, dict]) Path[source]#

Generates the Path needed for the agent marker using a variety of setup methods, depending on argument type:

  • Path is used as it is

  • dict is used to call Path

  • Patch already defines a path, which is extracted and used.

  • str is looked up in MARKERS; if no such entry is available, the remaining options are evaluated.

  • Other types construct a MarkerStyle from which the path is extracted.

After constructing the path, applies the base orientation by rotating it by that value.

_compute_size_factors(paths: Sequence[Path]) ndarray[source]#

Given a sequence of Paths, computes the corresponding size factors which are used in set_markersizes() to scale the individual marker sizes. The resulting sizes are multiplied with the given size scale.

If marker size normalization is activated, size factors may vary between the markers.

_add_to_offsets_history(new_offsets: ndarray) None[source]#

Adds the given offset to the left side of the deque, pushing old entries off the right side of the deque.

If the tail segment length is limited, will mask the offset positions for individual agents if they differ by more than that value from their previous position. Note that in this case the history is no longer strictly correct; it is already evaluated for use in draw_tails() in order to increase performance and avoid evaluating this over and over again.

_build_line_segments() ndarray[source]#

Creates the line segments for the tails using the offsets history

_rotate_path(path: Path, *, base_vertices: ndarray, orientation: float) None[source]#

Sets the given path’s vertices by rotating (a copy of) the base vertices by the given orientation (in radians).

set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, array=<UNSET>, capstyle=<UNSET>, clim=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, cmap=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, markersizes=<UNSET>, mouseover=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, orientations=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, visible=<UNSET>, zorder=<UNSET>)#

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or scalar or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of colors or ‘face’ facecolor or facecolors or fc: color or list of colors figure: ~matplotlib.figure.Figure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats markersizes: unknown mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: unknown orientations: unknown path_effects: list of .AbstractPathEffect paths: unknown picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float

class utopya.eval.plots.abm.HandlerAgentCollection(yoffsets=None, sizes=None, **kwargs)[source]#

Bases: HandlerPathCollection

Legend handler for AgentCollection instances.

create_collection(orig_handle, sizes, offsets, offset_transform) AgentCollection[source]#

Returns an AgentCollection from which legend artists are created.

create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source]#

Creates the artists themselves.

For original docstring see matplotlib.legend_handler.HandlerBase.create_artists().

utopya.eval.plots.abm._get_data(d: Union[DataArray, Dataset], var: str) DataArray[source]#

Retrieve data by key, e.g. for hue, size, …

utopya.eval.plots.abm._parse_vmin_vmax(specs: dict, d: Union[DataArray, Dataset], *, vmin_key: str = 'vmin', vmax_key: str = 'vmax') dict[source]#

Adapts specs dict entries vmin_key and vmax_key, replacing their values with the minimum or maximum value of given data d.

utopya.eval.plots.abm._set_domain(*, ax: matplotlib.axes.Axes, layers: dict, mode: str = 'auto', extent: Tuple[float, float, float, float] = None, height: float = None, aspect: Union[float, int, str] = 'auto', update_only: bool = False, pad: float = 0.05) Optional[Tuple[float, float]][source]#

Sets the axis limits and computes the area of the domain

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to adjust

  • layers (dict) – Layer information prepared by abmplot()

  • mode (str, optional) – Domain mode, can be auto, manual, fixed and follow. In fixed mode, all available data in layers is inspected to derive domain bounds. In follow mode, the currently used collection positions are used to determine the boundaries. In auto mode, will use a fixed domain if no extent was given, otherwise manual mode is used.

  • extent (Tuple[float, float, float, float], optional) – A manually set extent in form (left, right, bottom, top). Alternatively, a 2-tuple will be interpreted as (0, right, 0, top).

  • height (float, optional) – The height of the domain in data units

  • aspect (Union[float, int, str], optional) – The aspect ratio of the domain, the width being computed via height * aspect. If auto, will

  • update_only (bool, optional) – If true, will only make changes to the domain bounds if necessary, e.g. in follow mode.

  • pad (float, optional) – Relative padding added to each side.

Returns:

The domain area (in data units squared) and the aspect ratio, i.e. width/height. The return value will be None if update_only was set.

Return type:

Optional[Tuple[float, float]]

utopya.eval.plots.abm.draw_agents(d: Union[Dataset, DataArray], *, x: str, y: str, ax: matplotlib.axes.Axes = None, _collection: Optional[AgentCollection] = None, _domain_area: float = 1, marker: Union[Path, Patch, str, list, dict] = 'auto', hue: str = None, orientation: Union[str, float, Sequence[float]] = None, size: Union[str, float, Sequence[float]] = None, size_norm: Union[str, dict, matplotlib.colors.Normalize] = None, size_vmin: float = None, size_vmax: float = None, size_scale: float = 0.0005, label: str = None, cmap: Union[str, dict] = None, norm: Union[str, dict] = None, vmin: Union[float, str] = None, vmax: Union[float, str] = None, cbar_label: str = None, cbar_labels: dict = None, add_colorbar: bool = None, cbar_kwargs: dict = None, **coll_kwargs) AgentCollection[source]#

Draws agent positions onto the given axis.

Data can be a DataArray or Dataset with x, y and the other encodings hue, orientation and size being strings that denote

Parameters:
  • d (Union[xarray.Dataset, xarray.DataArray]) – The agent data. The recommended format is that of datasets, because it can hold more data variables. If using data arrays, multiple coordinates can be used to set the data. Also, the name attribute needs to be set (to avoid accidentally using the wrong data).

  • x (str) – Name of the data dimension or variable that holds x positions.

  • y (str) – Name of the data dimension or variable that holds y positions.

  • ax (matplotlib.axes.Axes, optional) – The axis to plot to; will use the current axis if not given.

  • _collection (Optional[AgentCollection], optional) – If a collection exists, will update this collection instead of creating a new one.

  • _domain_area (float, optional) – The domain area, used to normalize the marker sizes for a consistent visual appearance. This is only needed when initializing the collection and will set its size_scale parameter to size_scale * _domain_area.

  • marker (Union[matplotlib.path.Path, matplotlib.patches.Patch, str, list, dict], optional) – Which marker to use for the agents. See AgentCollection for available arguments.

  • hue (str, optional) – The name of the data dimension or variable that holds the values from which marker colors are determined.

  • orientation (Union[str, float, Sequence[float]], optional) – The name of the data variable or dimension that holds the orientation data (in radians). If scalar or sequence, will pass those explicit values through.

  • size (Union[str, float, Sequence[float]], optional) – The name of the data variable or dimension that holds the values from which the marker size is determined.

  • size_norm (Union[str, dict, matplotlib.colors.Normalize], optional) – A normalization for the sizes. The ColorManager is used to set up this normalization, thus offering all the corresponding capabilities. Actual sizes are computed by xarray.plot.utils._parse_size`.

  • size_vmin (float, optional) – The value that is mapped to the smallest size of the markers.

  • size_vmax (float, optional) – The value that is mapped to the largest size of the markers.

  • size_scale (float, optional) – A scaling factor that is applied to the size of all markers; use this to control overall size.

  • label (str, optional) – How to label the collection that is created. Will be used as default colorbar label and for the legend.

  • cmap (Union[str, dict], optional) – The colormap to use for the markers. Supports ColorManager.

  • norm (Union[str, dict], optional) – Norm to use for the marker colors. Supports ColorManager.

  • vmin (Union[float, str], optional) – The value of the hue dimension that is mapped to the beginning of the colormap.

  • vmax (Union[float, str], optional) – The value of the hue dimension that is mapped to the end of the colormap.

  • cbar_labels (dict, optional) – Colorbar labels, parsed by the ColorManager.

  • add_colorbar (bool, optional) – Whether to add a colorbar or not. Only used upon creating the collection.

  • cbar_kwargs (dict, optional) – Passed on to create_cbar()

  • **coll_kwargs – Passed on to AgentCollection; see there for further available arguments.

utopya.eval.plots.abm.abmplot(*, data: Dict[str, Union[Dataset, DataArray]], hlpr: PlotHelper, to_plot: Dict[str, dict], frames: Optional[str] = None, frames_isel: Optional[Union[int, slice]] = None, domain: Union[str, dict, Tuple[float, float, float, float]] = 'fixed', adjust_figsize_to_domain: bool = True, figsize_aspect_offset: float = 0.2, suptitle_fstr: str = '{dim:} = {val:5d}', suptitle_kwargs: dict = {'fontfamily': 'monospace'}, add_legend: Optional[bool] = None, **shared_kwargs)[source]#

Plots agents in a domain, animated over time.

Features:

  • Plot multiple “layers” of agents onto the same axis.

  • Encode hue, size and orientation of all agents.

  • Keep track of position history through an animation and draw the history as (constant or decaying) tails.

  • Automatically determine the domain bounds, allowing to dynamically follow the agents through the domain.

  • Generate marker paths ad-hoc or use pre-defined markers that are relevant in the context of visualizing agent-based models, e.g. fish.

Example output:

Development roadmap

The following extensions of this plot function are planned:

  • Subplot support, allowing to manually distribute to_plot entries onto individual subplots.

  • Faceting support, allowing to automatically distribute all data layers onto rows and columns and thus performing a dimensionality reduction on them.

Parameters:
  • data (Dict[str, Union[xarray.Dataset, xarray.DataArray]]) – A dict holding the data that is to be plotted.

  • hlpr (PlotHelper) – The plot helper instance.

  • to_plot (Dict[str, dict]) – Individual plot specifications. Each entry refers to one “layer” of agents being plotted and its key needs to match the corresponding entry in data. See draw_agents() for available arguments. Note that the shared_kwargs also end up in the entries here.

  • frames (str, optional) – Which data dimension to use for the animation.

  • frames_isel (Union[int, slice], optional) – An index-selector that is applied on the frames dimension (without dropping empty dimensions resulting from this operation). Scalar values will be wrapped into a list of size one.

  • domain (Union[str, dict, Tuple[float, float, float, float]], optional) – Specification of the domain on which the agents are plotted. If a 4-tuple is given, it defines the position of the fixed (left, right, bottom, top) borders of the domain; a 2-tuple will be interpreted as (0, right, 0, top). If a string is given, it determines the mode by which the domain is determined. It can be fixed (determine bounds from all agent positions, then keep them constant) or follow (domain dynamically follows agents, keeping them centered). If a dict is given, it is passed to _set_domain(), and offers more options like pad or aspect.

  • adjust_figsize_to_domain (bool, optional) – If True, will adjust the figure size to bring it closer to the aspect ratio of the domain, thus reducing whitespace.

  • figsize_aspect_offset (float, optional) – A constant offset that is added to the aspect ratio of the domain to arrive at the target aspect ratio of the figure used for adjust_figsize_to_domain.

  • suptitle_fstr (str, optional) – The format string to use for the figure’s super-title. If empty or None, no suptitle is added. The format string can include the following keys: dim (frames dimension name), val (current coordinate value, will be an index if no coordinates are available), coords (a dict containing all layers’ iterator states), and frame_no (enumerates the frame number).

  • suptitle_kwargs (dict, optional) – Passed to suptitle().

  • add_legend (bool, optional) – Whether to add a legend. ⚠️ This is currently experimental and does not work as expected.

  • **shared_kwargs – Shared keyword arguments for all plot specifications. Whatever is specified here is used as a basis for each individual layer in to_plot, i.e. updated by the entries in to_plot. See draw_agents() for available arguments.

utopya.eval.plots.attractor module#

This module provides plotting functions to visualize the attractive set of a dynamical system.

Todo

Migrate these to the more generic DAG-based interface.

utopya.eval.plots.attractor.bifurcation_diagram(dm: DataManager, *, hlpr: PlotHelper, mv_data: Dataset, dim: Optional[str] = None, dims: Optional[Tuple[str, str]] = None, analysis_steps: Sequence[Union[str, Tuple[str, str]]], custom_analysis_funcs: Optional[Dict[str, Callable]] = None, analysis_kwargs: Optional[dict] = None, visualization_kwargs: Optional[dict] = None, to_plot: Optional[dict] = None, **kwargs) None[source]#
Plots a bifurcation diagram for one or two parameter dimensions

(arguments dim or dims).

Parameters:
  • dm (DataManager) – The data manager from which to retrieve the data

  • hlpr (PlotHelper) – The PlotHelper that instantiates the figure and takes care of plot aesthetics (labels, title, …) and saving

  • mv_data (xarray.Dataset) – The extracted multidimensional dataset

  • dim (str, optional) – The required parameter dimension of the 1d bifurcation diagram.

  • dims (str, optional) – The required parameter dimensions (x, y) of the 2d-bifurcation diagram.

  • analysis_steps (Sequence) –

    The analysis steps that are to be made until one is conclusive. Applied per universe.

    • If seq of str: The str will also be used as attractor key for

      plotting if the test is conclusive.

    • If seq of Tuple(str, str): The first str defines the attractor

      key for plotting, the second str is a key within custom_analysis_funcs.

    Default analysis_funcs are:

    • endpoint: utopya.dataprocessing.find_endpoint

    • fixpoint: utopya.dataprocessing.find_fixpoint

    • multistability: utdp.find_multistability

    • oscillation: utdp.find_oscillation

    • scatter: resolve_scatter

  • custom_analysis_funcs (dict) – A collection of custom analysis functions that will overwrite the default analysis funcs (recursive update).

  • analysis_kwargs (dict, optional) – The entries need to match the analysis_steps. The subentry (dict) is passed on to the analysis function.

  • visualization_kwargs (dict, optional) – The entries need to match the analysis_steps. The subentry (dict) is used to configure a rectangle to visualize the conclusive analysis step. Is passed to matplotlib.patches.rectangle. xy, width, height, and angle are ignored and set automatically. Required in 2d bifurcation diagram.

  • to_plot (dict, optional) –

    The configuration for the data to plot. The entries of this key need to match the data_vars selected in mv_data. It is used to visualize the state of the attractor additionally to the visualization kwargs. Only for 1d-bifurcation diagram. sub_keys:

    • label (str, optional): label in plot

    • plot_kwargs (dict, optional): passed to scatter for every

      universe

      • color (str, recommended): unique color for every

        data_variable accross universes

  • **kwargs

    Collection of optional dicts passed to different functions

    • plot_coords_kwargs (dict): Passed to ax.scatter to mark the

      universe’s center in the bifurcation diagram

    • rectangle_map_kwargs (dict): Passed to

      utopya.eval.plots._utils.calc_pxmap_rectangles

    • legend_kwargs (dict): Passed to ax.legend

utopya.eval.plots.ca module#

This module provides plotting functions to visualize cellular automata.

utopya.eval.plots.ca._prepare_hexgrid_data(data: Union[ndarray, DataArray], *, x: Optional[str] = None, y: Optional[str] = None) Tuple[DataArray, str, str][source]#

Prepares data for imshow_hexagonal() by checking the given data and specified dimension names are consistent.

utopya.eval.plots.ca._flatten_hexgrid_data(data: DataArray) ndarray[source]#

Flattens hexgrid data in a specific way.

For consistency, this function should be used when calling set_array() on collections that represent hexagonal grid data.

utopya.eval.plots.ca._plot_ca_property(prop_name: str, *, hlpr: PlotHelper, data: DataArray, default_imshow_kwargs: dict, imshow_hexagonal_extra_kwargs: Optional[dict] = None, default_cbar_kwargs: Optional[dict] = None, grid_structure: Optional[str] = None, vmin: Optional[float] = None, vmax: Optional[float] = None, cmap: Optional[Union[dict, str]] = None, norm: Optional[Union[dict, str]] = None, add_colorbar: bool = True, set_axis_off: bool = True, title: Optional[str] = None, imshow_kwargs: Optional[dict] = None, cbar_labels: Optional[dict] = None, cbar_label_kwargs: Optional[dict] = None, cbar_tick_params: Optional[dict] = None, no_cbar_markings: bool = False, **cbar_kwargs) AxesImage[source]#

Helper function, used in caplot() to plot a property on the given axis. Returns the created axes image object.

Note

The arguments here are those within the individual entries of the to_plot argument for the above plotting functions.

Parameters:
  • prop_name (str) – The property to plot

  • hlpr (PlotHelper) – The plot helper

  • data (xarray.DataArray) – The array-like data to plot as an image

  • default_imshow_kwargs (dict) – Default arguments for the imshow call, updated with individually-specified imshow_kwargs.

  • imshow_hexagonal_extra_kwargs (dict) – Default arguments for hexagonal grids, ignored otherwise. This updates the default_imshow_kwargs and is in turn updated with individually-specified imshow_kwargs.

  • default_cbar_kwargs (dict) – Default arguments for the colorbar creation, updated with cbar_kwargs.

  • grid_structure (str, optional) – Can be used to explicitly set the grid structure in cases where data.attrs['grid_structure'] is not available or holds an invalid entry. This decides whether to use matplotlib.axes.Axes.imshow() or imshow_hexagonal(). Note that the grid_properties need to be passed via the imshow_kwargs argument below.

  • vmin (float, optional) – The lower limit to use for the colorbar range.

  • vmax (float, optional) – The upper limit to use for the colorbar range.

  • cmap (Union[str, dict], optional) – The colormap to use. If a dict is given, defines a (discrete) ListedColormap from the values. Handled by ColorManager.

  • norm (Union[str, dict], optional) – The normalization function to use. Handled by ColorManager.

  • add_colorbar (bool, optional) – If false, will not draw a colorbar. Default is true.

  • set_axis_off (bool, optional) – If true (default), will set the axis to invisible.

  • title (str, optional) – The subplot figure title

  • imshow_kwargs (dict, optional) – Depending on grid structure, is passed on either to imshow() or to imshow_hexagonal().

  • cbar_labels (dict, optional) – Passed to ColorManager to set up the label names alongside the given cmap and norm.

  • cbar_label_kwargs (dict, optional) – Passed to create_cbar() for controlling the aesthetics of colorbar labels.

  • cbar_tick_params (dict, optional) – Passed to create_cbar() for controlling the aesthetics of colorbar ticks.

  • no_cbar_markings (bool, optional) – Whether to suppress colorbar markings (ticks and tick labels).

  • **cbar_kwargs – Passed to create_cbar()

Returns:

The created axes image representing the CA property.

Return type:

matplotlib.image.AxesImage

Raises:

ValueError – on invalid grid structure; supported structures are square and hexagonal

utopya.eval.plots.ca.imshow_hexagonal(data: Union[DataArray, ndarray], *, ax: Optional[Axes] = None, x: Optional[str] = None, y: Optional[str] = None, grid_properties: dict = {}, update_grid_properties: dict = {}, grid_properties_keys: dict = {}, extent: Optional[tuple] = None, scale: float = 1.01, draw_centers: bool = False, draw_center_radius: float = 0.1, draw_center_kwargs: dict = {}, hide_ticks: Optional[bool] = None, cmap: Optional[str] = None, norm: Optional[str] = None, vmin: Optional[float] = None, vmax: Optional[float] = None, collection_kwargs: dict = {}, **im_kwargs) AxesImage[source]#

Visualizes data using a grid of hexagons (⬢ or ⬣).

Owing to the many ways in which a hexagonal grid can be visualized, this function requires more information than imshow(). These so called grid properties need to be passed via the grid_properties argument or directly alongside the data via data.attrs (for DataArray).

The following grid properties are available:

coordinate_mode (str):

In which way the data is stored. Currently only supports offset mode, i.e. with offset row and column coordinates. Coordinates of individual cells need not be given, nor can they be given: Assuming a regular hexagonal grid, all coordinates and sizes are completely deduced from the shape of the given data and the other grid parameters like pointy_top and offset_mode.

pointy_top (bool):

Whether the hexagons have a pointy top (⬢) or a flat top (⬣). More precisely, with a pointy top, there is only a single vertex at the top and bottom of the hexagon (i.e. along the y dimension and the top/bottom of the resulting plot).

offset_mode (str):

Whether even or odd rows or columns are offset towards higher values. In other words: For pointy tops, offset every second row toward the right. For flat tops, offset every second column towards the top. Offset distance is half a cell’s width and half a cell’s height, respectively.

space_size (Tuple[float, float], optional):

The size of the space in (width, height) that the hexagonal grid cells cover. If given, will make the assumption that the available number of hexagons in each dimension reach from one end of the space to the other, even if that means that the hexagons become distorted along the dimensions. If not given, will assume regular hexagons and use arbitrary units to cover the space; these hexagons will not be distorted.

space_offset (Tuple[float, float], optional):

Translates the space by (offset_x, offset_y). Also applies to the case where space_size was not given. Effectively, this refers to the coordinates of the bottom left-hand corner of the space.

space_boundary (str, optional):

Whether the space (regardless of explicitly given or deduced) describes the outer or inner boundary of the hexagonal grid. The outer boundary (default) goes through the outermost vertices of the outermost cells. The inner boundary goes through some hexagon center, cutting off pointy tops and protruding parts of the hexagons such that the whole space is covered by hexagonal cells.

For example, grid properties may look like this:

grid_properties:
  # -- Required:
  coordinate_mode: offset
  pointy_top: true
  offset_mode: even

  # -- Optional:
  space_size: [8, 8]
  space_offset: [-4, -4]
  space_boundary: outer

With some 2D dummy grid data of shape (21, 24), the corresponding output would be as follows. The darker cells denote the boundary and the corners; the lighter cells correspond to a “vertical” line in the third column of the grid.

../_images/small_with_space_outer.pdf

By setting the space boundary parameter to inner, the domain size remains the same, but the boundary cells are partially cut off:

../_images/small_with_space_inner.pdf

Removing all optional parameters, specifically the space_size, the size of the domain is arbitrary, so no labels are drawn. In addition, we can also mark the hexagon centers:

../_images/small_centers_marked.pdf

Changing to flat tops and odd offset mode results in a figure with a different aspect ratio, while the hexagons remain regular.

../_images/small_flat_top_odd.pdf

When specifying the domain size again, the hexagons need to be scaled non-uniformly to cover the domain:

../_images/small_flat_top_odd_with_space.pdf

Hint

For an excellent introduction to hexagonal grid representations, see this article.

See also

Parameters:
  • data (Union[xarray.DataArray, numpy.ndarray]) – 2D array-like data that holds the grid information that is to be plotted. If the data is given as DataArray, its attrs are used to update the given grid_properties.

  • ax (matplotlib.axes.Axes, optional) – The axes to draw to; if not given, will use the current axes.

  • x (str, optional) – Name of the data dimension that is to be represented on the x-axis of the plot. If not given, will use the first data dimension.

  • y (str, optional) – Name of the data dimension that is to be represented on the x-axis of the plot. If not given, will use the second data dimension.

  • grid_properties (dict, optional) – The grid properties dict, which needs to specify the above properties in order to determine how to represent the data. This dict is first updated with potentially available data.attrs and subsequently updated with the update_grid_properties.

  • update_grid_properties (dict, optional) – Updates the grid properties, see above.

  • grid_properties_keys (dict, optional) – A mapping that can be used if the given data has grid properties given under different names. For instance, {"space_size": "size"} would read the size entry instead of space_size.

  • extent (tuple, optional) – A custom space extent, denoting the edges (left, right, bottom, top) of the domain in data units.

  • scale (float, optional) – A scaling factor for the size of the hexagons. The default value is very slightly larger than 1 to reduce aliasing artefacts on exactly overlapping hexagon edges. Scaling is uniform.

  • draw_centers (bool, optional) – Whether to additionally draw the center points of all hexagons.

  • draw_center_radius (float, optional) – The relative radius of the center points in units of min(cell_width, cell_height) / 2.

  • draw_center_kwargs (dict, optional) – Additional arguments that are passed to the PatchCollection used to draw the center points.

  • hide_ticks (bool, optional) – Whether to hide the ticks and tick labels. If None, will hide ticks if no space_size grid property was given (in which case the units are assumed irrelevant).

  • cmap (str, optional) – The colormap to use

  • norm (str, optional) – The normalization to use

  • vmin (float, optional) – The minimum value of the color range to use

  • vmax (float, optional) – The maximum value of the color range to use

  • collection_kwargs (dict, optional) – Passed on to the PolyCollection that is used to represent the hexagons.

  • **im_kwargs – Passed on to matplotlib.image.AxesImage that is created from the whole axis. Can be used to set interpolation or similar options.

Returns:

The imshow-like object containing the hexagonal grid.

Return type:

matplotlib.image.AxesImage

utopya.eval.plots.ca.caplot(*, hlpr: PlotHelper, data: dict, to_plot: Dict[str, dict], from_dataset: Optional[Dataset] = None, frames: str = 'time', frames_isel: Optional[Union[int, Sequence]] = None, grid_structure: Optional[str] = None, aspect: float = 1.0, aspect_pad: float = 0.1, size: Optional[float] = None, col_wrap: Union[int, str, bool] = 'auto', imshow_hexagonal_extra_kwargs: Optional[dict] = None, default_imshow_kwargs: Optional[dict] = None, default_cbar_kwargs: dict = {'aspect': 20, 'fraction': 0.04}, suptitle_fstr: str = '{} = {}', suptitle_kwargs: Optional[dict] = None)[source]#

Plots an animated series of one or many 2D Cellular Automata states.

The data used for plotting is assembled from data using the keys that are specified in to_plot. Alternatively, the from_dataset argument can be used to pass a dataset which contains all the required data.

The keys in to_plot should match the names of data variables. The values in to_plot specify the individual subplots’ properties like the color map that is to be used or the minimum or maximum values.

For plotting square grids, matplotlib.axes.Axes.imshow() is used and generates output like this:

../_images/snapshot_square.pdf

For a grid with hexagonal cells, imshow_hexagonal() is used; more details on how the cells are mapped to the space can be found there. The output (for the same dummy data as used above) may look like this:

../_images/snapshot_hex.pdf

Finally, this plot function is specialized to generate animations along the frames dimension of the data, e.g. time:

Requirements on the CA data

The selected data (keys in to_plot that correspond to DAG results in data) should have two spatial dimensions and one data dimension that goes along the frames dimension.

All coordinates should be identical, otherwise the behavior is not defined or alignment might fail.

For hexagonal grid structure, note the requirements given in imshow_hexagonal().

Parameters:
  • hlpr (PlotHelper) – The plot helper instance

  • data (dict) – The selected data

  • to_plot (Dict[str, dict]) –

    Which data to plot and how. The keys of this dict refer to an item within the selected data or the given dataset. Each of these keys is expected to hold yet another dict, supporting the following configuration options (all optional):

    • title (str, optional):

      The title for this sub-plot.

    • cmap (Union[str, list, dict], optional):

      Which colormap to use. This argument is handled by the ColorManager, providing many ways in which to define the colormap. For instance, by passing mapping from labels to colors, a discrete colormap is created: The keys will be the labels and the values will be their colors. Association happens in the order of entries, with values being inferred from vmin and vmax, if given. For more information and examples, see the docstring of the ColorManager.

    • norm (Union[str, dict], optional):

      The normalization function to use, also handled by the ColorManager.

    • vmin (float, optional):

      The fixed lower data limit for this property; if not given, uses auto-scaling, which may lead to jumps in the animation. Can also be 'min' in which case the global minimum of the available data is used.

    • vmax (float, optional):

      Same as vmin, but with the maximum and allowing 'max' argument for choosing the global maximum.

    • label (str, optional):

      The colorbar label.

    • imshow_kwargs (dict, optional):

      Passed on to the imshow invocation, i.e. to imshow() or imshow_hexagonal().

    • **kwargs:

      Further arguments control the colorbar appearance, their labels, ticks, and other plot specifics. For more detailed information about available arguments, see _plot_ca_property(), which takes care of plotting the individual to_plot entries.

  • from_dataset (xarray.Dataset, optional) – If given, will use this object instead of assembling a dataset from data and to_plot keys.

  • frames (str, optional) – Name of the animated dimension, typically the time dimension.

  • frames_isel (Union[int, Sequence], optional) – The index selector for the frames dimension. Can be a single integer but also a range expression.

  • grid_structure (str, optional) – The underlying grid structure, can be square, hexagonal, or triangular (not implemented). If None, will try to read it from the individual properties’ data attribute grid_structure.

  • aspect (float, optional) – The aspect ratio (width/height) of the subplots; should match the aspect ratio of the data.

  • aspect_pad (float, optional) – A factor that is added to the calcuation of the subplots width. This can be used to create a horizontal padding between subplots.

  • size (float, optional) – The height in inches of a subplot. Is used to determine the subplot size with the width being calculated by size * (aspect + aspect_pad).

  • col_wrap (Union[int, str, bool], optional) – Controls column wrapping. If auto, will compute a column wrapping that leads to an (approximately) square subplots layout (not taking into account the subplots aspect ratio, only the grid layout). This will start producing a column wrapping with four or more properties to plot.

  • default_imshow_kwargs (dict, optional) – The default parameters passed to the underlying imshow plotting function. These are updated by the values given via to_plot.

  • default_cbar_kwargs (dict, optional) – The default parameters for the colorbar that is added to applicable subplots. These are updated by the parameters given under to_plot.

  • suptitle_fstr (str, optional) – A format string used to create the suptitle string. Passed arguments are frames and the currently selected frames coordinate (not the index!). If this evaluates to False, will not create a figure suptitle.

  • suptitle_kwargs (dict, optional) – Passed on to fig.suptitle.

utopya.eval.plots.distributions module#

DAG-based distribution plotting functions

utopya.eval.plots.distributions.histogram(*, data: dict, hlpr: PlotHelper, x: str, hue: Optional[str] = None, frames: Optional[str] = None, coarsen_by: Optional[int] = None, align: str = 'edge', bin_widths: Optional[Union[str, Sequence[float]]] = None, suptitle_kwargs: Optional[dict] = None, show_histogram_info: bool = True, **bar_kwargs)[source]#

Shows a distribution as a stacked bar plot, allowing animation.

Expects as DAG result counts an xr.DataArray of one, two, or three dimensions. Depending on the hue and frames arguments, this will be represented as a stacked barplot and as an animation, respectively.

Parameters:
  • data (dict) – The DAG results

  • hlpr (PlotHelper) – The PlotHelper

  • x (str) – The name of the dimension that represents the position of the histogram bins. By default, these are the bin centers.

  • hue (str, optional) – Which dimension to represent by stacking bars of different hue on top of each other

  • frames (str, optional) – Which dimension to represent by animation

  • coarsen_by (int, optional) – By which factor to coarsen the dimension specified by x. Uses xr.DataArray.coarsen and pads boundary values.

  • align (str, optional) – Where to align bins. By default, uses edge for alignment, as this is more exact for histograms.

  • bin_widths (Union[str, Sequence[float]], optional) – If not given, will use the difference between the x coordinates as bin widths, padding on the right side using the last value If a string, assume that it is a DAG result and retrieve it from data. Otherwise, use it directly for the width argument of plt.bar, i.e. assume it’s a scalar or a sequence of bin widths.

  • suptitle_kwargs (dict, optional) – Description

  • show_histogram_info (bool, optional) – Whether to draw a box with information about the histogram.

  • **bar_kwargs – Passed on hlpr.ax.bar invocation

Returns:

None

Raises:

ValueError – Bad dimensionality or missing bin_widths DAG result

utopya.eval.plots.graph module#

This module provides graph plotting functions.

utopya.eval.plots.graph.graph_array_from_group(graph_group: utopya.eval.groups.GraphGroup, *, graph_creation: dict = None, register_property_maps: dict = None, clear_existing_property_maps: bool = True, times: dict = None, sel: dict = None, isel: dict = None) DataArray[source]#

From a utopya.eval.groups.GraphGroup creates a xarray.DataArray with object dtype, containing the networkx.Graph objects created from the graph group at the specified points in the group’s coordinate space.

From all coordinates provided via the selection kwargs the cartesian product is taken. Each of those points represents one entry in the returned xarray.DataArray. The selection kwargs in graph_creation are ignored silently.

Parameters:
  • graph_group (utopya.eval.groups.GraphGroup) – The graph group to create the graph array from

  • graph_creation (dict, optional) – Graph creation configuration

  • register_property_maps (dict, optional) – Property maps to be registered before graph creation

  • clear_existing_property_maps (bool, optional) – Whether to remove any existing property map at first

  • times (dict, optional) – Equivalent to a sel.time entry. (Deprecated!)

  • sel (dict, optional) – Select by value

  • isel (dict, optional) – Select by index

Returns:

networkx.Graph with the respective graph

group coordinates

Return type:

xarray.DataArray

utopya.eval.plots.graph.graph_animation_update(*, hlpr: PlotHelper, graphs: Optional[DataArray] = None, graph_group=None, graph_creation: Optional[dict] = None, register_property_maps: Optional[dict] = None, clear_existing_property_maps: bool = True, positions: Optional[dict] = None, animation_kwargs: Optional[dict] = None, suptitle_kwargs: Optional[dict] = None, suptitle_formatter: Optional[Callable] = None, **drawing_kwargs)[source]#

Graph animation frame generator. Yields whenever the plot helper may grab the current frame.

If graphs is given, the networkx graphs in the array are used to create the frames.

Otherwise, use a graph group. The frames are defined via the selectors in animation_kwargs. From all provided coordinates the cartesian product is taken. Each of those points defines one graph and thus one frame. The selection kwargs in graph_creation are ignored silently.

Parameters:
  • hlpr (PlotHelper) – The plot helper

  • graphs (xarray.DataArray, optional) – Networkx graphs to draw. The array will be flattened beforehand.

  • graph_group (None, optional) – Required if graphs is None. The GraphGroup from which to generate the animation frames as specified via sel and isel in animation_kwargs.

  • graph_creation (dict, optional) – Graph creation configuration. Passed to create_graph_from_group() if graph_group is given.

  • register_property_maps (dict, optional) – Passed to create_graph_from_group() if graph_group is given.

  • clear_existing_property_maps (bool, optional) – Passed to create_graph_from_group() if graph_group is given.

  • positions (dict, optional) – The node position configuration. If update_positions is True the positions are reconfigured for each frame.

  • animation_kwargs (dict, optional) –

    Animation configuration. The following arguments are allowed:

    times (dict, optional):

    Deprecated: Equivaluent to a sel.time entry.

    sel (dict, optional):

    Select by value. Coordinate values (or from_property entry) keyed by dimension name.

    isel (dict, optional):

    Select by index. Coordinate indices keyed by dimension. May be given together with sel if no key appears in both.

    update_positions (bool, optional):

    Whether to reconfigure the node positions for each frame (default=False).

    update_colormapping (bool, optional):

    Whether to reconfigure the nodes’ and edges’ ColorManager for each frame (default=False). If False, the colormapping (and the colorbar) is configured with the first frame and then fixed.

    skip_empty_frames (bool, optional):

    Whether to skip the frames where the selected graph is missing or of a type different than nx.Graph (default=False). If False, such frames are empty.

  • suptitle_kwargs (dict, optional) – Passed on to the PlotHelper and its set_suptitle helper function. Only used in animation mode. The title can be a format string containing a placeholder with the dimension name as key for each dimension along which selection is done. The format string is updated for each frame of the animation. The default is <dim-name> = {<dim-name>} for each dimension.

  • **drawing_kwargs – Passed to GraphPlot

utopya.eval.plots.graph.draw_graph(*, hlpr: PlotHelper, data: dict, graph_group_tag: str = 'graph_group', graph: Optional[Union[Graph, DataArray]] = None, graph_creation: Optional[dict] = None, graph_drawing: Optional[dict] = None, graph_animation: Optional[dict] = None, register_property_maps: Optional[Sequence[str]] = None, clear_existing_property_maps: bool = True, suptitle_kwargs: Optional[dict] = None, suptitle_formatter: Optional[Callable] = None)[source]#

Draws a graph either from a GraphGroup or directly from a networkx.Graph using the GraphPlot class.

If the graph object is to be created from a graph group the latter needs to be selected via the TransformationDAG. Additional property maps can also be made available for plotting, see register_property_map argument. Animations can be created either from a graph group by using the select interface in graph_animation or by passing a DataArray of networkx graphs via the graph argument.

For more information on how to use the transformation framework, refer to the dantro documentation and its TransformationDAG class.

For more information on how to configure the graph layout refer to the GraphPlot documentation.

Parameters:
  • hlpr (PlotHelper) – The PlotHelper instance for this plot

  • data (dict) – Data from TransformationDAG selection

  • graph_group_tag (str, optional) – The TransformationDAG tag of the graph group

  • graph (Union[networkx.Graph, xarray.DataArray], optional) – If given, the data and graph_creation arguments are ignored and this graph is drawn directly. If a DataArray of graphs is given, the first graph is drawn for a single graph plot. In animation mode the (flattened) array represents the animation frames.

  • graph_creation (dict, optional) – Configuration of the graph creation. Passed to GraphGroup.create_graph.

  • graph_drawing (dict, optional) – Configuration of the graph layout. Passed to GraphPlot.

  • graph_animation (dict, optional) –

    Animation configuration. The following arguments are allowed:

    times (dict, optional):

    Deprecated: Equivaluent to a sel.time entry.

    sel (dict, optional):

    Select by value. Dictionary with dimension names as keys. The values may either be coordinate values or a dict with a from_property (str) entry which specifies a container within the GraphGroup or registered external data from which the coordinates are extracted. Additionally, there can be isel and sel keys beside the from_property key, performing a subselection on those coordinates.

    isel (dict, optional):

    Select by index. Coordinate indices keyed by dimension. May be given together with sel if no key appears in both.

    update_positions (bool, optional):

    Whether to update the node positions for each frame by recalculating the layout with the parameters specified in graph_drawing.positions. If this parameter is not given or false, the positions are calculated once initially and then fixed.

    update_colormapping (bool, optional):

    Whether to reconfigure the nodes’ and edges’ ColorManager for each frame (default=False). If False, the colormapping (and the colorbar) is configured with the first frame and then fixed.

    skip_empty_frames (bool, optional):

    Whether to skip the frames where the selected graph is missing or of a type different than networkx.Graph (default=False). If False, such frames are empty.

  • register_property_maps (Sequence[str], optional) – Names of properties to be registered in the graph group before the graph creation. The property names must be valid TransformationDAG tags, i.e., be available in data. Note that the tags may not conflict with any valid path reachable from inside the selected GraphGroup.

  • clear_existing_property_maps (bool, optional) – Whether to clear any existing property maps from the selected GraphGroup. This is enabled by default to reduce side effects from previous plots. Set this to False if you have property maps registered with the GraphGroup that you would like to keep.

  • suptitle_kwargs (dict, optional) – Passed on to the PlotHelper’s set_suptitle helper function. Only used in animation mode. The title can be a format string containing a placeholder with the dimension name as key for each dimension along which selection is done. The format string is updated for each frame of the animation. The default is <dim-name> = {<dim-name>} for each dimension.

  • suptitle_formatter (Callable, optional) – If given, this should be a function that takes coordinates and their values as keyword arguments and returns the string that is to be used as the title. Only used in animation mode.

Raises:

ValueError – On invalid or non-computed TransformationDAG tags in register_property_maps or invalid graph group tag.

utopya.eval.plots.snsplot module#

Implements seaborn-based plotting functions

utopya.eval.plots.snsplot.snsplot(*, data: dict, hlpr: PlotHelper, sns_kind: str, free_indices: Tuple[str, ...], optional_free_indices: Tuple[str, ...] = (), auto_encoding: Optional[Union[bool, dict]] = None, reset_index: bool = False, to_dataframe_kwargs: Optional[dict] = None, dropna: bool = False, dropna_kwargs: Optional[dict] = None, sample: Union[bool, int] = False, sample_kwargs: Optional[dict] = None, **plot_kwargs) None[source]#

Interface to seaborn’s figure-level plot functions. Plot functions are selected via the sns_kind argument:

Parameters:
  • data (dict) – The data transformation framework results, expecting a single entry data which can be a pandas.DataFrame or an xarray.DataArray or xarray.Dataset.

  • hlpr (PlotHelper) – The plot helper instance

  • sns_kind (str) – Which seaborn plot to use, see list above.

  • free_indices (Tuple[str]) – Which index names not to associate with a layout encoding; seaborn uses these to calculate the distribution statistics.

  • optional_free_indices (Tuple[str], optional) – These indices will be added to the free indices if they are part of the data frame. Otherwise, they are silently ignored.

  • auto_encoding (Union[bool, dict], optional) – Auto-encoding options.

  • reset_index (bool, optional) – Whether to reset indices such that only the free_indices remain as indices and all others are converted into columns.

  • to_dataframe_kwargs (dict, optional) – For xarray data types, this is used to convert the given data into a pandas.DataFrame.

  • sample (bool, optional) – If True, will sample a subset from the final dataframe, controlled by sample_kwargs

  • sample_kwargs (dict, optional) – Passed to pandas.DataFrame.sample().

  • **plot_kwargs – Passed on to the selected plotting function.

utopya.eval.plots.time_series module#

A generic, DAG-supporting time series plot

utopya.eval.plots.time_series.time_series(*, data: dict, hlpr: PlotHelper, x: str = 'time', label_fstr: str = '{:.2g}', **plot_kwargs)[source]#

This is a generic plotting function that plots one or multiple time series from the data tag that is selected via the DAG framework.

The data needs to be an xarray object. If y is an xr.DataArray, it is assumed to be one- or two-dimensional. If is an xarray.Dataset, all data variables are plotted and their name is used as the label.

For the x axis values, the corresponding time coordinates are used; these need to be part of the dataset!

Note

For a more generic plot, see dantro’s facet_grid(), which is available under .plot.facet_grid in utopya.

Parameters:
  • data (dict) – The data selected by the DAG framework

  • hlpr (PlotHelper) – The plot helper

  • x (str, optional) – Name of the coordinate dimension to put on the x-axis, typically (and by default) time.

  • label_fstr (str, optional) – Formatting to use for label in case of the data being an xarray.DataArray.

  • **plot_kwargs – Passed on ot matplotlib.pyplot.plot().