utopya.plot_funcs 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.plot_funcs._basic module

Common code for plot functions in the basic_uni and basic_mv modules

utopya.plot_funcs._file_writer module

This module provides plotting functions to visualize cellular automata.

NOTE This module is deprecated and will be removed!

class utopya.plot_funcs._file_writer.FileWriter(*, file_format: str = 'png', name_padding: int = 6, fstr: str = '{dir:}/{num:0{pad:}d}.{ext:}', **savefig_kwargs)[source]

Bases: object

The FileWriter class yields functionality to save individual frames.

It adheres to the corresponding matplotlib animation interface.

Initialize a FileWriter, which adheres to the matplotlib.animation interface and can be used to write individual files.

Parameters
  • name_padding (int, optional) – How wide the numbering should be

  • file_format (str, optional) – The file extension

  • fstr (str, optional) – The format string to generate the name

  • **savefig_kwargs – kwargs to pass to figure.savefig

__init__(*, file_format: str = 'png', name_padding: int = 6, fstr: str = '{dir:}/{num:0{pad:}d}.{ext:}', **savefig_kwargs)[source]

Initialize a FileWriter, which adheres to the matplotlib.animation interface and can be used to write individual files.

Parameters
  • name_padding (int, optional) – How wide the numbering should be

  • file_format (str, optional) – The file extension

  • fstr (str, optional) – The format string to generate the name

  • **savefig_kwargs – kwargs to pass to figure.savefig

saving(fig, base_outfile: str, **kwargs)[source]

Create an instance of the context manager

grab_frame()[source]

Stores a single frame

__dict__ = mappingproxy({'__module__': 'utopya.plot_funcs._file_writer', '__doc__': 'The FileWriter class yields functionality to save individual frames.\n\n    It adheres to the corresponding matplotlib animation interface.\n    ', '__init__': <function FileWriter.__init__>, 'saving': <function FileWriter.saving>, 'grab_frame': <function FileWriter.grab_frame>, '__dict__': <attribute '__dict__' of 'FileWriter' objects>, '__weakref__': <attribute '__weakref__' of 'FileWriter' objects>, '__annotations__': {}})
__module__ = 'utopya.plot_funcs._file_writer'
__weakref__

list of weak references to the object (if defined)

class utopya.plot_funcs._file_writer.FileWriterContextManager(*, fig, out_dir: str, **kwargs)[source]

Bases: object

This class is needed by the file writer to provide the same interface as the matplotlib movie writers do.

__init__(*, fig, out_dir: str, **kwargs)[source]
__enter__()[source]

Called when entering context

__exit__(*args)[source]

Called when exiting context

__dict__ = mappingproxy({'__module__': 'utopya.plot_funcs._file_writer', '__doc__': 'This class is needed by the file writer to provide the same interface\n    as the matplotlib movie writers do.\n    ', '__init__': <function FileWriterContextManager.__init__>, '__enter__': <function FileWriterContextManager.__enter__>, '__exit__': <function FileWriterContextManager.__exit__>, '__dict__': <attribute '__dict__' of 'FileWriterContextManager' objects>, '__weakref__': <attribute '__weakref__' of 'FileWriterContextManager' objects>, '__annotations__': {}})
__module__ = 'utopya.plot_funcs._file_writer'
__weakref__

list of weak references to the object (if defined)

utopya.plot_funcs._graph module

This module provides the GraphPlot class.

class utopya.plot_funcs._graph.GraphPlot(g: networkx.classes.graph.Graph, *, fig=None, ax=None, select: Optional[dict] = None, positions: Optional[dict] = None, nodes: Optional[dict] = None, edges: Optional[dict] = None, node_labels: Optional[dict] = None, edge_labels: Optional[dict] = None, mark_nodes: Optional[dict] = None, mark_edges: Optional[dict] = None)[source]

Bases: object

The GraphPlot class provides an interface for visualizing a networkx.Graph object or a graph created from a GraphGroup via matplotlib.

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 (nx.Graph) – The associated networkx graph

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

  • ax (None, optional) – The matplotlib axis 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.

    If installed, GraphViz models can be selected with a prepended graphviz_. Options depend on the GraphViz version but may include: dot, neato, fdp, sfdp, twopi, circo. (Passed as prog to networkx.graphviz_layout).

    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.

__init__(g: networkx.classes.graph.Graph, *, fig=None, ax=None, select: Optional[dict] = None, positions: Optional[dict] = None, nodes: Optional[dict] = None, edges: Optional[dict] = None, node_labels: Optional[dict] = None, edge_labels: Optional[dict] = None, mark_nodes: Optional[dict] = None, mark_edges: Optional[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 (nx.Graph) – The associated networkx graph

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

  • ax (None, optional) – The matplotlib axis 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.

    If installed, GraphViz models can be selected with a prepended graphviz_. Options depend on the GraphViz version but may include: dot, neato, fdp, sfdp, twopi, circo. (Passed as prog to networkx.graphviz_layout).

    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 the GraphPlot instance.

Returns

The networkx graph object

Return type

nx.Graph

draw(*, fig=None, ax=None, positions: Optional[dict] = None, nodes: Optional[dict] = None, edges: Optional[dict] = None, node_labels: Optional[dict] = None, edge_labels: Optional[dict] = None, mark_nodes: Optional[dict] = None, mark_edges: Optional[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 GraphPlot.

Parameters
  • fig (None, optional) – matplotlib figure

  • ax (None, 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, *, graph_creation: Optional[dict] = None, register_property_maps: Optional[dict] = None, clear_existing_property_maps: bool = True, **init_kwargs)[source]

Initializes a GraphPlot from a GraphGroup.

Parameters
  • graph_group – 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 GraphPlot

static create_graph_from_group(graph_group, *, register_property_maps: Optional[dict] = None, clear_existing_property_maps: bool = True, **graph_creation) networkx.classes.graph.Graph[source]

Creates a networkx.Graph from a GraphGroup. Additional property maps may be added to the group beforehand.

Parameters
  • graph_group – The GraphGroup.

  • 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 create_graph().

Returns

The created networkx.Graph object.

Return type

nx.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 (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.

  • 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 nx.draw_networkx_nodes when calling draw()

parse_edges(*, width=None, edge_color=None, edge_cmap=None, cmap_norm=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 nx.draw_networkx_edges when calling draw().

Raises

TypeError – On norm type other than mpl.colors.Normalize 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

__dict__ = mappingproxy({'__module__': 'utopya.plot_funcs._graph', '__doc__': 'The ``GraphPlot`` class provides an interface for visualizing a \n    ``networkx.Graph`` object or a graph created from a\n    :py:class:`~utopya.datagroup.GraphGroup` via matplotlib.\n    ', '__init__': <function GraphPlot.__init__>, 'g': <property object>, 'draw': <function GraphPlot.draw>, 'add_colorbars': <function GraphPlot.add_colorbars>, 'clear_plot': <function GraphPlot.clear_plot>, 'from_group': <classmethod object>, 'create_graph_from_group': <staticmethod object>, 'parse_positions': <function GraphPlot.parse_positions>, 'parse_nodes': <function GraphPlot.parse_nodes>, 'parse_edges': <function GraphPlot.parse_edges>, 'parse_node_labels': <function GraphPlot.parse_node_labels>, 'parse_edge_labels': <function GraphPlot.parse_edge_labels>, 'mark_nodes': <function GraphPlot.mark_nodes>, 'mark_edges': <function GraphPlot.mark_edges>, '_configure_node_patch_sizes': <function GraphPlot._configure_node_patch_sizes>, '_scale_to_interval': <staticmethod object>, '_select_subgraph': <function GraphPlot._select_subgraph>, '__dict__': <attribute '__dict__' of 'GraphPlot' objects>, '__weakref__': <attribute '__weakref__' of 'GraphPlot' objects>, '__annotations__': {}})
__module__ = 'utopya.plot_funcs._graph'
__weakref__

list of weak references to the object (if defined)

utopya.plot_funcs._mpl_helpers module

This module provides matplotlib-related helper constructs

class utopya.plot_funcs._mpl_helpers.ColorManager(*, cmap: Optional[Union[str, dict, matplotlib.colors.Colormap]] = None, norm: Optional[Union[str, dict, matplotlib.colors.Normalize]] = None, labels: Optional[dict] = None, vmin: Optional[float] = None, vmax: Optional[float] = None)[source]

Bases: object

Custom color manager which provides an interface to the matplotlib.colors module.

Initializes the ColorManager by building the colormap, the norm, and the colorbar labels.

Parameters
  • cmap (Union[str, dict, mpl.colors.Colormap], optional) –

    The colormap. If it is a string, it must name a registered colormap. If it is a dict, the following arguments are available:

    name (str, optional):

    Name of a registered colormap.

    from_values (Union[dict, list], optional):

    Dict of colors keyed by bin-specifier. If given, name is ignored and a discrete colormap is created from the list of specified colors. The norm is then set to BoundaryNorm.

    The bins can be specified either by bin-centers (Scalar) or by bin-intervals (2-tuples). For the former, the deduced bin-edges are assumed halfway between the bin-centers. For the latter, the given intervals must be pairwise connected. In both cases, the bins must monotonically increase.

    If a list of colors is passed they are automatically assigned to the bin-centers [0, 1, 2, ...].

    under (Union[str, dict], optional):

    Passed on to Colormap.set_under.

    over (Union[str, dict], optional):

    Passed on to Colormap.set_over.

    bad (Union[str, dict], optional):

    Passed on to Colormap.set_bad.

    placeholder_color (optional): None values in

    from_values are replaced with this color (default: white).

  • norm (Union[str, dict, mpl.colors.Normalize], optional) – The norm that is applied for the color-mapping. If it is a string, the matching norm in matplotlib.colors is created with default values. If it is a dict, the name entry specifies the norm and all further entries are passed to its constructor. Overwritten if a discrete colormap is specified via cmap.from_values.

  • labels (Union[dict, list], optional) – Colorbar tick-labels keyed by tick position. If a list of labels is passed they are automatically assigned to the positions [0, 1, 2, …].

  • vmin (float, optional) – The lower bound of the color-mapping. Ignored if norm is BoundaryNorm.

  • vmax (float, optional) – The upper bound of the color-mapping. Ignored if norm is BoundaryNorm.

__init__(*, cmap: Optional[Union[str, dict, matplotlib.colors.Colormap]] = None, norm: Optional[Union[str, dict, matplotlib.colors.Normalize]] = None, labels: Optional[dict] = None, vmin: Optional[float] = None, vmax: Optional[float] = None)[source]

Initializes the ColorManager by building the colormap, the norm, and the colorbar labels.

Parameters
  • cmap (Union[str, dict, mpl.colors.Colormap], optional) –

    The colormap. If it is a string, it must name a registered colormap. If it is a dict, the following arguments are available:

    name (str, optional):

    Name of a registered colormap.

    from_values (Union[dict, list], optional):

    Dict of colors keyed by bin-specifier. If given, name is ignored and a discrete colormap is created from the list of specified colors. The norm is then set to BoundaryNorm.

    The bins can be specified either by bin-centers (Scalar) or by bin-intervals (2-tuples). For the former, the deduced bin-edges are assumed halfway between the bin-centers. For the latter, the given intervals must be pairwise connected. In both cases, the bins must monotonically increase.

    If a list of colors is passed they are automatically assigned to the bin-centers [0, 1, 2, ...].

    under (Union[str, dict], optional):

    Passed on to Colormap.set_under.

    over (Union[str, dict], optional):

    Passed on to Colormap.set_over.

    bad (Union[str, dict], optional):

    Passed on to Colormap.set_bad.

    placeholder_color (optional): None values in

    from_values are replaced with this color (default: white).

  • norm (Union[str, dict, mpl.colors.Normalize], optional) – The norm that is applied for the color-mapping. If it is a string, the matching norm in matplotlib.colors is created with default values. If it is a dict, the name entry specifies the norm and all further entries are passed to its constructor. Overwritten if a discrete colormap is specified via cmap.from_values.

  • labels (Union[dict, list], optional) – Colorbar tick-labels keyed by tick position. If a list of labels is passed they are automatically assigned to the positions [0, 1, 2, …].

  • vmin (float, optional) – The lower bound of the color-mapping. Ignored if norm is BoundaryNorm.

  • vmax (float, optional) – The upper bound of the color-mapping. Ignored if norm is BoundaryNorm.

property cmap
property norm
property labels
__dict__ = mappingproxy({'__module__': 'utopya.plot_funcs._mpl_helpers', '__doc__': 'Custom color manager which provides an interface to the\n    ``matplotlib.colors`` module.\n    ', '__init__': <function ColorManager.__init__>, 'cmap': <property object>, 'norm': <property object>, 'labels': <property object>, '_parse_boundaries': <function ColorManager._parse_boundaries>, '_create_cmap': <function ColorManager._create_cmap>, '_create_norm': <function ColorManager._create_norm>, 'map_to_color': <function ColorManager.map_to_color>, 'create_cbar': <function ColorManager.create_cbar>, '__dict__': <attribute '__dict__' of 'ColorManager' objects>, '__weakref__': <attribute '__weakref__' of 'ColorManager' objects>, '__annotations__': {}})
__module__ = 'utopya.plot_funcs._mpl_helpers'
__weakref__

list of weak references to the object (if defined)

map_to_color(X)[source]

Maps the input data to color(s) by applying both norm and colormap.

Parameters

X (Union[scalar, ndarray]) – The data value(s) to convert to RGBA.

Returns

Tuple of RGBA values if X is scalar, otherwise an array of RGBA values with a shape of X.shape + (4, ).

create_cbar(mappable, *, fig=None, ax=None, label: Optional[str] = None, label_kwargs: Optional[dict] = None, tick_params: Optional[dict] = None, **cbar_kwargs)[source]

Creates a colorbar.

Parameters
  • mappable – The matplotlib.cm.ScalarMappable described by the colorbar.

  • fig (None, optional) – The figure

  • ax (None, optional) – The axis

  • label (str, optional) – A label for the colorbar

  • label_kwargs (dict, optional) – Additional parameters passed to cb.set_label.

  • tick_params (dict, optional) – Set colorbar tick parameters via cb.ax.tick_params

  • **cbar_kwargs – Passed on to fig.colorbar.

  • tick_params

Returns

The created colorbar.

utopya.plot_funcs._utils module

Utility functions that assist plot functions

utopya.plot_funcs._utils.calc_pxmap_rectangles(*, x_coords: numpy.ndarray, y_coords: numpy.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[xarray.core.dataset.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 (np.ndarray) – The x coordinates

  • y_coords (np.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

xr.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[xr.Dataset, Dict[str, tuple]]

utopya.plot_funcs.attractor module

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

utopya.plot_funcs.attractor.bifurcation_diagram(dm: utopya.datamanager.DataManager, *, hlpr: utopya.plotting.PlotHelper, mv_data: xarray.core.dataset.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 (xr.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.plot_funcs._utils.calc_pxmap_rectangles

    • legend_kwargs (dict): Passed to ax.legend

utopya.plot_funcs.basic_mv module

Implements basic generic multiverse plot functions

utopya.plot_funcs.basic_mv.errorbar(dm: utopya.datamanager.DataManager, *, mv_data: xarray.core.dataset.Dataset, hlpr: utopya.plotting.PlotHelper, to_plot: str = 'data', transform_data: Optional[Tuple[Union[dict, str]]] = None, lines_from: Optional[str] = None, plot_std: Union[str, bool] = False, transform_std: Optional[Tuple[Union[dict, str]]] = None, transformations_log_level: int = 10, cmap: Optional[str] = None, **errorbar_kwargs)[source]

Perform an errorbar plot from the selected multiverse data.

This plot, ultimately, requires 1D data, where the remaining dimension is plotted on the x-axis. The transform_data or lines_from arguments can be used to work with higher-dimensional data.

Parameters
  • dm (DataManager) – The data manager

  • mv_data (xr.Dataset) – The extracted multidimensional data

  • hlpr (PlotHelper) – The plot helper

  • to_plot (str, optional) – Which data variable from mv_data to plot. The data needs to be 1D. If it is not 1D, you can apply the transform argument to make it 1D. Alternatively, the lines_from argument can be given, in which case 2D data is allowed.

  • transform_data (Tuple[Union[dict, str]], optional) – Apply transformations to the to_plot data in mv_data. With the parameters specified here, multiple transformations can be applied. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to selecting a slice. For available parameters, see utopya.dataprocessing.transform()

  • lines_from (str, optional) – A valid dimension name over which to iterate in order to plot multiple errorbar lines. If None, only a single line is plotted.

  • plot_std (Union[str, bool], optional) – Which entry of the mv_data to use for plotting the standard deviation. If True, the mean data will be used. If False, no standard deviation is plotted.

  • transform_std (Tuple[Union[dict, str]], optional) – Like transform_data, but applied to the data selected in plot_std

  • transformations_log_level (int, optional) – With which log level to perform the transformations. Useful for debugging.

  • cmap (str, optional) – If given, the lines created from lines_from will be colored according to this color map

  • **errorbar_kwargs – Passed on to plt.errorbar

utopya.plot_funcs.basic_mv.asymptotic_average(dm: utopya.datamanager.DataManager, *, mv_data: xarray.core.dataset.Dataset, hlpr: utopya.plotting.PlotHelper, average_dim: str, average_fraction: float, data_variable: str = 'data', plot_std: bool = True, transform_data: Optional[Tuple[Union[dict, str]]] = None, transformations_log_level: int = 10, **errorbar_kwargs)[source]

Plots asymptotically averaged single values.

After transform_data, the data_variable in mv_data should be a 2D array where one of the dimensions is average_dim. All data from the other dimension are plotted as single points with standard deviation.

Parameters
  • dm (DataManager) – The data manager

  • mv_data (xr.Dataset) – The selected multiverse data

  • hlpr (PlotHelper) – The PlotHelper

  • average_dim (str) – The name of the dimension to average over.

  • average_fraction (float) – Which fraction of the dimension specified in average_dim to use for averaging. If it is desired to make this absolute, choose 1. and use transform_data to select a smaller slice of the data.

  • data_variable (str, optional) – Name of the data variable from mv_data to use for plotting.

  • transform_data (Tuple[Union[str, dict]], optional) – Applied to the data array from mv_data.

  • transformations_log_level (int, optional) – Log level of transformation operations.

  • **errorbar_kwargs – Passed to plt.errorbar

Raises

ValueError – On data that is not 2D or does not contain a time dimension

utopya.plot_funcs.basic_uni module

Implements basic generic plot universe plot functions

utopya.plot_funcs.basic_uni.lineplot(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, path_to_data: Union[str, Tuple[str, str]], transform_data: Optional[dict] = None, transformations_log_level: int = 10, **plot_kwargs)[source]

Performs an errorbar plot of a specific universe.

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

  • uni (UniverseGroup) – The data for this universe

  • hlpr (PlotHelper) – The PlotHelper

  • model_name (str) – The name of the model the data resides in

  • path_to_data (str or Tuple[str, str]) – The path to the data within the model data or the paths to the x and the y data, respectively

  • transform_data (dict, optional) – Transformations to apply to the data. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to selecting a slice. For available parameters, see utopya.dataprocessing.transform()

  • transformations_log_level (int, optional) – The log level of all the transformation operations.

  • **plot_kwargs – Passed on to plt.plot

Raises
  • ValueError – On invalid data dimensionality

  • ValueError – On mismatch of data shapes

utopya.plot_funcs.basic_uni.lineplots(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, to_plot: dict, **common_plot_kwargs)[source]

Like lineplot, but for several specifications given by the to_plot argument.

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

  • uni (UniverseGroup) – The selected universe data

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

  • model_name (str) – The name of the model the data resides in, i.e. the base path within the UniverseGroup.

  • to_plot (dict) – Which data to plot. The keys of this dict are used as path_to_data for the lineplot function. The values are unpacked and passed to lineplot. Alternatively, the path_to_data can be given explicitly, which e.g. allows plotting individual columns of the same data container.

  • **common_plot_kwargs – Passed along to the lineplot plot function for all calls. Note that this may not contain any keys that are given within to_plot!

utopya.plot_funcs.basic_uni.errorbar_single(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, path_to_data: str, transform_data: Optional[Tuple[Union[dict, str]]] = None, plot_std: Union[str, bool] = False, transform_std: Optional[Tuple[Union[dict, str]]] = None, transformations_log_level: int = 10, **errorbar_kwargs)[source]

Plot of a single error bar line

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

  • uni (UniverseGroup) – The data for this universe

  • hlpr (PlotHelper) – The PlotHelper

  • model_name (str) – The name of the model the data resides in

  • path_to_data (str) – The path to the data within the model data

  • transform_data (Tuple[Union[dict, str]], optional) – Apply transformations to the to_plot data in mv_data. With the parameters specified here, multiple transformations can be applied. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to selecting a slice. For available parameters, see utopya.dataprocessing.transform()

  • plot_std (Union[str, bool], optional) – Either a boolean or a path to dataset within the model to use for plotting the standard deviation. If True, the mean data will be used. If False, no standard deviation is plotted.

  • transform_std (Tuple[Union[dict, str]], optional) – Like transform_data, but applied to the data selected in plot_std.

  • transformations_log_level (int, optional) – With which log level to perform the transformations. Useful for debugging.

  • **errorbar_kwargs – Passed on to plt.errorbar

utopya.plot_funcs.basic_uni.errorbar(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, to_plot: dict, cmap: Optional[str] = None, transformations_log_level: int = 10, **errorbar_kwargs)[source]

Perform an errorbar plot from the selected multiverse data.

This plot, ultimately, requires 1D data, where the remaining dimension is plotted on the x-axis. The transform_data or lines_from arguments can be used to work with higher-dimensional data.

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

  • uni (UniverseGroup) – The data for this universe

  • hlpr (PlotHelper) – The PlotHelper

  • model_name (str) – The common name of the model the data resides in. Can be overwritten by information in to_plot.

  • to_plot (dict) – A dict of specifications of lines to plot. For details see utopya.plot_funcs.basic_uni.errorbar_single().

  • cmap (str, optional) – If given, the lines created from to_plot will be colored according to this color map.

  • transformations_log_level (int, optional) – The log level of all transformation operations specified in each to_plot entry.

  • **errorbar_kwargs – Passed on to plt.errorbar

Deleted Parameters:

mv_data (xr.Dataset): The extracted multidimensional data

utopya.plot_funcs.basic_uni.distance_map(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, path_to_data: str, transform_data: Optional[dict] = None, transformations_log_level: int = 10, cbar_kwargs: Optional[dict] = None, **plot_kwargs)[source]

Creates a distance map of data at t_0 to data at t_1.

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

  • uni (UniverseGroup) – The data for this universe

  • hlpr (PlotHelper) – The PlotHelper

  • model_name (str) – The name of the model the data resides in

  • path_to_data (str) – The path to the data within the model data

  • transform_data (dict, optional) – Transformations to apply to the data. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to selecting a slice. For available parameters, see utopya.dataprocessing.transform()

  • transformations_log_level (int, optional) – The log level of all the transformation operations.

  • cbar_kwargs (dict, optional) – Passed on to fig.colorbar

  • **plot_kwargs – Passed on to ax.matshow

Raises

ValueError – On invalid data dimensionality

utopya.plot_funcs.ca module

This module provides plotting functions to visualize cellular automata.

utopya.plot_funcs.ca.imshow_hexagonal(data: xarray.core.dataarray.DataArray, *, hlpr: utopya.plotting.PlotHelper, colormap: Union[str, matplotlib.colors.Colormap], **kwargs) matplotlib.image.AxesImage[source]

Display data as an image, i.e., on a 2D hexagonal grid.

Parameters
  • data (xr.DataArray) – The array-like data to plot as image.

  • hlpr (PlotHelper) – The plot helper.

  • colormap (str or mpl.colors.Colormap) – The colormap to use.

Returns

The RegularPolyCollection representing the hexgrid.

utopya.plot_funcs.ca.state(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, to_plot: dict, time_idx: int, transform_data: Optional[dict] = None, transformations_log_level: int = 10, preprocess_funcs: Optional[Dict[str, Callable]] = None, default_imshow_kwargs: Optional[dict] = None)[source]

Plots the state of the cellular automaton as a 2D heat map. This plot function can be used for a single plot, but also supports animation.

Which properties of the state to plot can be defined in to_plot.

Parameters
  • dm (DataManager) – The DataManager that holds all loaded data

  • uni (UniverseGroup) – The currently selected universe, parsed by the UniversePlotCreator.

  • hlpr (PlotHelper) – The plot helper

  • model_name (str) – The name of the model of which the data is to be plotted

  • to_plot (dict) –

    Which data to plot and how. The keys of this dict refer to a path within the data and can include forward slashes to navigate to data of submodels. Each of these keys is expected to hold yet another dict, supporting the following configuration options (all optional):

    • cmap (str or dict): The colormap to use. If it is a dict, a

      discrete colormap is assumed. The keys will be the labels and the values the color. Association happens in the order of entries.

    • title (str): The title for this sub-plot

    • limits (2-tuple, list): The fixed heat map limits of this

      property; if not given, limits will be auto-scaled.

    • **imshow_kwargs: passed on to imshow invocation

  • time_idx (int) – Which time index to plot the data of. Is ignored when creating an animation.

  • transform_data (dict, optional) – Transformations to apply to the data. The top-level entries must correspond to the entries of to_plot. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to selecting a slice. For available parameters, see utopya.dataprocessing.transform()

  • transformations_log_level (int, optional) – The logging level of all the data transformation operations.

  • preprocess_funcs (Dict[str, Callable], optional) – A dictionary of pre- processing callables, where keys need to correspond to the property name in to_plot that is to be pre-processed. This argument can be used to implement model-specific preprocessing by implementing another plot function, which defines this dict and passes it to this function. NOTE If possible, use transform_data.

  • 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.

Raises

ValueError – Shape mismatch of data selected by to_plot

Warns

Use of transform_data and preprocess_funcs (is called in this order)

utopya.plot_funcs.distribution module

This module provides plotting functions to visualize distributions.

utopya.plot_funcs.distribution.histogram(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, path_to_data: str, histogram_kwargs: Optional[dict] = None, use_unique: bool = False, preprocess: Optional[Tuple[Union[dict, str]]] = None, postprocess: Optional[Tuple[Union[dict, str]]] = None, mask_repeated: bool = False, show_histogram_info: bool = True, transformations_log_level: int = 10, pyplot_func_name: str = 'bar', **pyplot_func_kwargs)[source]

Calculates a histogram from the data and plots it.

This function is very versatile. Its capabilities range from a plain old histogram (only required arguments set) to the plot of a complementary cumulative probability distribution function.

Don’t despair. The documentation of arguments below should give a good idea of what each parameter does.

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

  • uni (UniverseGroup) – The selected universe data

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

  • model_name (str) – The model name that the data resides in

  • path_to_data (str) – The path to the data relative to the model data output

  • histogram_kwargs (dict, optional) – Passed to np.histogram. This can be used to adjust the number of bins or set the range the bins should be spread over; the latter also allows to pass a 2-tuple containing None, which will be resolved to data.min() or data.max(). See np.histogram documentation for other arguments.

  • use_unique (bool, optional) – If this option is set, will not do a regular histogram but count unique values.

  • preprocess (Tuple[Union[dict, str]], optional) – Apply pre-processing transformations to the selected data. With the parameters specified here, multiple transformations can be applied. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to select a slice. The operations are carried out before calculating the histogram. For available parameters, see utopya.dataprocessing.transform()

  • postprocess (Tuple[Union[dict, str]], optional) – Same as preprocess but applied _after_ the histogram was computed.

  • mask_repeated (bool, optional) – In use_unique mode, will mask the counts such that repeated values are not shown.

  • show_histogram_info (bool, optional) – Whether to show an info box in the top right-hand corner

  • transformations_log_level (int, optional) – With which log level to perform the transformations. Useful for debugging.

  • pyplot_func_name (str, optional) – The name of the matplotlib.pyplot function to use for plotting. By default, a bar plot is performed. For unique data, it might make more sense to do a line or scatter plot. Note that for the bar plot, the bar widths are automatically passed to the plot call and can not be adjusted.

  • **pyplot_func_kwargs – The kwargs passed on to the pyplot function chosen via the pyplot_func_name argument.

Raises

ValueError – When trying to make a bar plot with use_unique option enabled.

utopya.plot_funcs.time_series module

This module holds time-series plotting functions.

These plotting functions have in common, that they represent some kind of time series. The time may be visualized on the x-axis or in some other way, e.g. via the color of scatter points.

utopya.plot_funcs.time_series.density(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, path_to_data: str, mean_of: Tuple[str], preprocess: Optional[Tuple[Union[dict, str]]] = None, transformations_log_level: int = 10, sizes_from: Optional[str] = None, size_factor: float = 1.0, **plot_kwargs) None[source]

Plot the density of a mask, i.e. of a dataset holding booleans.

This plotting function is useful when creating a plot from data that is encoded in a binary fashion, e.g.: arrays containing True to denote the existence of some entity or some value and False to denote its absence.

If the dataset chosen via path_to_data is not already of boolean data type, the preprocess argument is to be used to generate the array-like boolean. By means of this argument, a binary operation of form data <operator> rhs_value is carried out, which results in the desired mask.

Another feature of this plotting function is that it can include another data source to use for the sizes of the plots; in that case, a scatter plot rather than a line plot is carried out.

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

  • uni (UniverseGroup) – The selected universe data

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

  • model_name (str) – The name of the model the data resides in, i.e. the base path within the UniverseGroup.

  • path_to_data (str) – Which data to use as the mask

  • mean_of (Tuple[str], optional) – which data dimensions to calculate the density over. If this evaluates to False, the operation will be skipped

  • preprocess (Tuple[Union[str, dict]], optional) – Apply pre-processing transformations to the selected data. With the parameters specified here, multiple transformations can be applied to the data. This can be used for dimensionality reduction of the data, but also for other operations, e.g. to select only a slice of the data. See utopya.dataprocessing.transform() for more info. NOTE The operations are carried out _before_ calculating the density over the parameters specified in mean_of. The preprocess ing should not be used for calculating the mean.

  • transformations_log_level (int, optional) – With which log level to perform the preprocess. Useful for debugging.

  • sizes_from (str, optional) – If given, this is expected to be the path to a dataset that contains size values for a scatter plot. This leads to a scatter rather than a line-plot. The sizes are not used directly but are normalized by dividing with the maximum size; this makes configuration via the size_factor parameter feasible.

  • size_factor (float, optional) – The factor by which to scale the sizes given in the sizes_from argument.

  • **plot_kwargs – Passed on to plt.plot or plt.scatter

Raises

ValueError – If the selected data is not a boolean mask. This error can be alleviated by providing the preprocess argument.

Returns

Description

Return type

None

utopya.plot_funcs.time_series.densities(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, to_plot: dict, **common_plot_kwargs)[source]

Like density, but for several specifications given by the to_plot argument.

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

  • uni (UniverseGroup) – The selected universe data

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

  • model_name (str) – The name of the model the data resides in, i.e. the base path within the UniverseGroup.

  • to_plot (dict) – Which data to plot the densities of. The keys of this dict are used as path_to_data for the density function. The values are unpacked and passed to density

  • **common_plot_kwargs – Passed along to the density plot function for all calls. Note that this may not contain any keys that are given within to_plot!

utopya.plot_funcs.time_series.phase_space(dm: utopya.datamanager.DataManager, *, uni: utopya.datagroup.UniverseGroup, hlpr: utopya.plotting.PlotHelper, model_name: str, x: str, y: str, cmap: Optional[str] = None, **scatter_kwargs)[source]

Plots x and y data in a phase space plot. If cmap is given, the time development will be colour coded.

Note

This automatically calculates the mean over all but the time dimension of the data.

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

  • uni (UniverseGroup) – The universe from which to plot the data

  • hlpr (PlotHelper) – The PlotHelper instance

  • model_name (str) – The model name from which to take the data

  • x (str) – The path to the data relative to the model_name which to plot on the x axis of the phase space plot.

  • y (str) – The path to the data relative to the model_name which to plot on the x axis of the phase space plot

  • cmap (str, optional) – The cmap which is used to color-code the time development. If not given, will not color-code it.

  • **scatter_kwargs – Passed on to plt.scatter