ml4cps.vis module¶
The module provides methods to visualize various kinds of data, such as time series or automata graphs.
Authors: - Nemanja Hranisavljevic, hranisan@hsu-hh.de, nemanja@ai4cps.com - Tom Westermann, tom.westermann@hsu-hh.de, tom@ai4cps.com
- ml4cps.vis.plot2d(df, x=None, y=None, mode='markers', hovercolumns=None, figure=False, **args)¶
- Creates a 2D scatter or line plot using Plotly based on the provided DataFrame columns. :param df: The input DataFrame containing the data to plot. :type df: pd.DataFrame :param x: The column name to use for the x-axis. :type x: str, optional :param y: The column name to use for the y-axis. :type y: str, optional :param mode: The Plotly scatter mode (e.g., ‘markers’, ‘lines’). Defaults to ‘markers’. :type mode: str, optional :param hovercolumns: List of column names to include in the hover tooltip. :type hovercolumns: list of str, optional :param figure: If True, returns a Plotly Figure object; otherwise, returns a Scatter trace. Defaults to False. :type figure: bool, optional :param **args: Additional keyword arguments passed to the Plotly Scatter constructor. - Returns:
- The generated Plotly Scatter trace or Figure, depending on the ‘figure’ parameter. 
- Return type:
- plotly.graph_objs._scatter.Scatter or plotly.graph_objs._figure.Figure 
 - Example - plot2d(df, x=’feature1’, y=’feature2’, hovercolumns=[‘label’], mode=’markers’, figure=True) 
- ml4cps.vis.plot3d(df, x=None, y=None, z=None, mode='markers', hovercolumns=None, **args)¶
- Creates a 3D scatter plot using Plotly’s Scatter3d, with customizable axes, hover information, and additional plot arguments. :param df: The data source containing columns for x, y, z, and optional hover data. :type df: pandas.DataFrame :param x: The column name in df to use for the x-axis. :type x: str, optional :param y: The column name in df to use for the y-axis. :type y: str, optional :param z: The column name in df to use for the z-axis. :type z: str, optional :param mode: Plotly scatter mode (e.g., ‘markers’, ‘lines’). Defaults to ‘markers’. :type mode: str, optional :param hovercolumns: List of column names in df to include in the hover tooltip. :type hovercolumns: list of str, optional :param **args: Additional keyword arguments passed to go.Scatter3d. - Returns:
- A Plotly 3D scatter plot object configured with the specified data and options. 
- Return type:
- plotly.graph_objs._scatter3d.Scatter3d 
 
- ml4cps.vis.plot_2d_contour_from_fun(fun, rangex=None, rangey=None, th=50, **kwargs)¶
- Plots a 2D contour of a function over a specified range. :param fun: A function that takes a 2D array of shape (n_points, 2) and returns a 1D array of function values. :type fun: callable :param rangex: The range for the x-axis as (min, max). Defaults to (-5, 5) if not provided. :type rangex: tuple, optional :param rangey: The range for the y-axis as (min, max). Defaults to (-5, 5) if not provided. :type rangey: tuple, optional :param th: Unused parameter, kept for compatibility. Defaults to 50. :type th: int, optional :param **kwargs: Additional keyword arguments passed to the plotly.graph_objs.Contour constructor. - Returns:
- A Plotly contour plot object representing the function values over the specified range. 
- Return type:
- plotly.graph_objs.Contour 
 
- ml4cps.vis.plot_cps(cps: CPS, dash_id=None, node_labels=False, edge_labels=True, node_size=40, node_font_size=20, edge_font_size=16, edge_text_max_width=None, output='cyto', dash_port=8050, height='100%', minZoom=0.5, maxZoom=2, **kwargs)¶
- Plots all the components of a CPS in the same figure. :param cps: CPS to plot. :param node_labels: Should node labels be plotted. :param edge_labels: Should edge labels be plotted. :param node_size: What is the size of the nodes in the figure. :param node_font_size: The font size of the node labels. :param edge_font_size: The font size of the edge labels. :param edge_text_max_width: Max width of the edge labels. :param output: Should output be plotted as a dash.Cytoscape component (“cyto”), or should dash server be run (“dash”). :param dash_port: If temporary dash server is run, what port to use. :param kwargs: Other paramters are forwarded to the Cytoscape component. :return: 
- ml4cps.vis.plot_cps_component(cps, id=None, node_labels=False, center_node_labels=False, event_label=True, show_transition_freq=False, show_transition_timing=False, font_size=6, edge_font_size=6, edge_text_max_width=None, init_label=False, limit_interval_precision=None, show_transition_data=False, node_size=20, output='cyto', dash_port=8050, min_zoom=0.5, max_zoom=1, min_edge_thickness=0.1, max_edge_thickness=4, freq_as_edge_thickness=False, color='black', title_text=None, layout_name='cose')¶
- Visualizes a component of a Cyber-Physical System (CPS) as a graph using Dash Cytoscape. This function generates a graphical representation of the discrete states and transitions of a CPS, with various customization options for node and edge appearance, labels, and output format. The visualization can be rendered as Dash Cytoscape elements, in a Dash app, or as a notebook widget. :param cps: object - The CPS object containing discrete states, transitions, and related data. - Parameters:
- id – str, optional The unique identifier for the Cytoscape component (default: “graph”). 
- node_labels – bool, optional Whether to display labels on nodes (default: False). 
- center_node_labels – bool, optional Whether to center node labels (default: False). 
- edge_labels – bool, optional Whether to display labels on edges (default: True). 
- show_transition_freq – bool, optional Whether to show transition frequency on edge labels (default: False). 
- edge_font_size – int, optional Font size for edge labels (default: 6). 
- edge_text_max_width – int or None, optional Maximum width for edge label text wrapping (default: None). 
- init_label – bool, optional Whether to label initial state transitions as ‘init’ (default: False). 
- show_transition_data – bool or list, optional Whether to display additional transition data on edge labels. If a list, only specified keys are shown (default: False). 
- node_size – int, optional Size of the nodes (default: 20). 
- output – str, optional Output format: “cyto” (Dash Cytoscape Div), “elements” (raw elements), “notebook” (inline Dash app), or “dash” (Dash app in browser) (default: “cyto”). 
- dash_port – int, optional Port for running the Dash app (default: 8050). 
- min_zoom – float, optional Minimum zoom level for the Cytoscape component (default: 0.5). 
- max_zoom – float, optional Maximum zoom level for the Cytoscape component (default: 1). 
- min_edge_thickness – float, optional Minimum edge thickness for frequency-based scaling (default: 0.1). 
- max_edge_thickness – float, optional Maximum edge thickness for frequency-based scaling (default: 4). 
- freq_as_edge_thickness – bool, optional Whether to scale edge thickness based on transition frequency (default: False). 
- color – str, optional Color for nodes and edges (default: “black”). If “hsu”, uses a preset color. 
- title_text – str or Dash component, optional Title text or component to display above the graph (default: None). 
 
- Returns:
- If output == “cyto”: returns a Dash html.Div containing the Cytoscape graph. 
- If output == “elements”: returns a dict with ‘nodes’ and ‘edges’. 
- If output == “notebook”: runs and displays a Dash app inline (for Jupyter). 
- If output == “dash”: runs a Dash app in the browser and returns the app instance. 
 
- Return type:
- Dash component, dict, or Dash app 
 - Notes - Requires Dash, dash_cytoscape, dash_bootstrap_components, and pandas. 
- The function supports interactive modals for displaying timing data on states and transitions. 
- Threading is used to launch the Dash app in browser mode without blocking the main program. 
 
- ml4cps.vis.plot_cps_plotly(cps, layout='dot', marker_size=20, node_positions=None, show_events=True, show_num_occur=False, show_state_label=True, font_size=10, plot_self_transitions=True, use_previos_node_positions=False, **kwargs)¶
- Visualizes a Cyber-Physical System (CPS) state-transition graph using Plotly. This function generates an interactive Plotly figure representing the states and transitions of a CPS. Nodes represent system states, and edges represent transitions. Various layout algorithms and display options are supported. :param cps: The CPS object containing the state-transition graph. Must have attributes _G (networkx graph), - get_transitions(), print_state(), num_occur(), and previous_node_positions. - Parameters:
- layout (str, optional) – Layout algorithm for node positioning. Options are “dot” (default), “spectral”, “kamada_kawai”, or “fruchterman_reingold”. 
- marker_size (int, optional) – Size of the node markers. Default is 20. 
- node_positions (dict, optional) – Precomputed node positions as a dictionary {node: (x, y)}. If None, positions are computed using the selected layout. 
- show_events (bool, optional) – Whether to display event labels on transitions. Default is True. 
- show_num_occur (bool, optional) – Whether to display the number of occurrences for each transition. Default is False. 
- show_state_label (bool, optional) – Whether to display state labels on nodes. Default is True. 
- font_size (int, optional) – Font size for transition/event labels. Default is 10. 
- plot_self_transitions (bool, optional) – Whether to plot self-loop transitions. Default is True. 
- use_previos_node_positions (bool, optional) – If True and node_positions is None, reuse positions from cps.previous_node_positions. Default is False. 
- **kwargs – Additional keyword arguments passed to the layout function (e.g., for networkx layouts). 
 
- Returns:
- A Plotly figure object representing the CPS state-transition graph. 
- Return type:
- plotly.graph_objs.Figure 
 - Notes - Requires Plotly, NetworkX, and pydotplus (for “dot” layout). 
- The CPS object must provide the required methods and attributes as described above. 
- Edge and node styling can be further customized by modifying the function. 
 
- ml4cps.vis.plot_dash_frames(graph_frames, dash_port=8050)¶
- Launches an interactive Dash web application to visualize a sequence of graph frames with a slider for manual frame selection. :param graph_frames: A list of Dash components (e.g., Cytoscape graphs) representing different frames to display. :type graph_frames: list :param dash_port: The port number on which to run the Dash server. Defaults to 8050. :type dash_port: int, optional - Returns:
- The Dash application instance. 
- Return type:
- dash.Dash 
 - Side Effects:
- Starts a Dash server in a separate thread. 
- Opens the default web browser to display the Dash app. 
- Waits for user input before returning. 
 
 - Notes - The app displays the first frame by default and allows users to select other frames using a slider. 
- The function blocks until the user presses Enter in the console. 
 
- ml4cps.vis.plot_execution_tree(graph, nodes_to_color, color, font_size=30)¶
- Plots a system execution tree as a graph, where the horizontal position of nodes corresponds to their timestamps and the tree branches vertically. :param graph: A directed graph where each node represents a system state, and edges represent transitions. - Each node should have a ‘label’ (str) and ‘weight’ (int) attribute. Node names must be timestamp strings in the format “%d/%m/%Y, %H:%M:%S”. - Parameters:
- nodes_to_color (list) – List of node identifiers (timestamp strings) to be highlighted with a specific color. 
- color (str) – The color to use for highlighting nodes in nodes_to_color. 
- font_size (int, optional) – Font size for node labels in the visualization. Defaults to 30. 
 
- Returns:
- A Dash Cytoscape object representing the execution tree visualization, with nodes positioned by timestamp and colored as specified. 
- Return type:
- cyto.Cytoscape 
 - Notes - The function assumes the first node in graph.nodes is the starting node. 
- Node positions are determined by the time difference from the start node (x-axis) and their ‘weight’ attribute (y-axis). 
- Nodes in nodes_to_color are colored with the specified color; all others are gray. 
- Requires the cyto (Dash Cytoscape) library and datetime module. 
 
- ml4cps.vis.plot_state_transitions(ta, state, obs=None)¶
- Visualizes the outgoing state transitions from a given state in a timed automaton, along with associated observation data. :param ta: An object representing the timed automaton, expected to have an out_transitions(state) method that returns transitions from the given state. :param state: The current state for which outgoing transitions and associated observations are to be visualized. :param obs: A pandas DataFrame containing observation data. Must include at least the columns ‘Mode’, ‘q_next’, ‘Duration’, ‘Time’, and optionally ‘Vergussgruppe’, ‘HID’, ‘ChipID’, ‘Order’, and ‘ArtNr’. If None, the function raises NotImplemented. :type obs: optional - Returns:
- A Plotly figure object containing subplots for each outgoing transition. For each transition, the function displays:
- A scatter plot of observation durations over time, grouped by ‘Vergussgruppe’. 
- A histogram of durations for each ‘Vergussgruppe’. 
 
 - The subplots are arranged with shared axes and appropriate titles for each transition. 
- Return type:
- fig 
- Raises:
- NotImplemented – If obs is None. 
 - Notes - The function expects certain columns to exist in the obs DataFrame. If missing, default values are assigned. 
- Colors for different ‘Vergussgruppe’ groups are assigned from DEFAULT_PLOTLY_COLORS. 
- The function uses Plotly’s make_subplots, go.Scatter, and go.Histogram for visualization. 
 
- ml4cps.vis.plot_stateflow(stateflow, color_mapping=None, state_col='State', bar_height=12, start_column='Start', finish_column='Finish', return_figure=False, description_col='Description', idle_states=None)¶
- Visualizes state transitions over time for one or more tasks/stations as a Gantt-like interactive timeline. - Parameters: - stateflow (DataFrame or dict): DataFrame with state transitions, or a dictionary of DataFrames per station. - color_mapping (dict, optional): Mapping of state names to colors. If None, default colors are used. - state_col (str): Column name indicating the state (default: ‘State’). - bar_height (int): Height of the timeline bars (default: 12). - start_column (str): Column name with start timestamps (default: ‘Start’). - finish_column (str): Column name with end timestamps (default: ‘Finish’). - return_figure (bool): If True, returns a Plotly Figure. Otherwise, returns a list of Plotly traces. - description_col (str or list): Column(s) to include in the hover tooltip (default: ‘Description’). - idle_states (str or list): State(s) to exclude from the plot (e.g., ‘IDLE’). - Returns: - Plotly Figure or list of traces, depending on return_figure. - Example - fig = plot_stateflow(df, state_col=’Mode’, start_column=’StartTime’, finish_column=’EndTime’, return_figure=True) fig.show() - This function is ideal for visualizing process flows, machine states, or event-based logs with time intervals. 
- ml4cps.vis.plot_timeseries(data, timestamp=None, mode_data=None, discrete=False, title=None, use_columns=None, height=None, limit_num_points=None, names=None, xaxis_title=None, customdata=None, iterate_colors=True, y_title_font_size=14, opacity=1, vertical_spacing=0.005, sharey=False, bounds=None, plot_only_changes=False, yAxisLabelOffset=False, marker_size=4, showlegend=False, mode='lines+markers', mode_height=0.2, x_title=None, **kwargs)¶
- Using plotly library, plots each variable (column) in a collection of dataframe as subplots, one after another. - Arguments: yAxisLabelOffset (bool): if True, adds an offset to the plots y-axis labels. Improves readability on long subplot names. - Return type:
- fig (plotly.Figure) 
 
- ml4cps.vis.plot_transition(self, s, d)¶
- Plots the transition histogram between two states. Retrieves the transition data between the source state s and destination state d, and generates a Plotly figure visualizing the timing distribution of the transition. The plot includes a title, an annotation indicating the transition, and a histogram of the transition timings. :param s: The source state identifier. :param d: The destination state identifier. - Returns:
- A Plotly Figure object containing the histogram of transition timings. 
- Return type:
- plotly.graph_objs._figure.Figure 
 
- ml4cps.vis.view_graphviz(self, layout='dot', marker_size=20, node_positions=None, show_events=True, show_num_occur=False, show_state_label=True, font_size=10, plot_self_transitions=True, use_previos_node_positions=False, **kwargs)¶
- Visualizes the internal graph structure using Graphviz and returns a pydot graph object. :param layout: The layout algorithm to use for node positioning (default: “dot”). :type layout: str :param marker_size: Size of the node markers in the visualization (default: 20). :type marker_size: int :param node_positions: Optional dictionary mapping node names to (x, y) positions. If None, positions are computed. :type node_positions: dict or None :param show_events: Whether to display event labels on transitions (default: True). :type show_events: bool :param show_num_occur: Whether to display the number of occurrences for each transition (default: False). :type show_num_occur: bool :param show_state_label: Whether to display state labels on nodes (default: True). :type show_state_label: bool :param font_size: Font size for labels and annotations (default: 10). :type font_size: int :param plot_self_transitions: Whether to plot self-loop transitions (default: True). :type plot_self_transitions: bool :param use_previos_node_positions: Whether to reuse previously computed node positions (default: False). :type use_previos_node_positions: bool :param **kwargs: Additional keyword arguments for customization. - Returns:
- A pydot graph object representing the visualized graph. 
- Return type:
- pdp.Dot 
 - Notes - Node positions are either computed using Graphviz or taken from the provided/previous positions. 
- Annotations for transitions can include event names and/or occurrence counts. 
- The function prepares the graph for further rendering or export, but does not display it directly.