OnionNet package

Contents

OnionNet package#

Submodules#

onionnet.builder module#

class onionnet.builder.OnionNetBuilder(core)#

Bases: object

Builder class for ingesting DataFrames into an OnionNetGraph.

Parameters:

core (OnionNetGraph)

core#

The core graph object where nodes and edges will be added.

Type:

OnionNetGraph

add_edges_from_dataframe(df_edges, source_id_col, source_layer_col, target_id_col, target_layer_col, property_cols=None, drop_na=True, fill_na_with=None, string_override=False, property_types=None)#

Add edges to the graph from a DataFrame containing edge information.

This method processes the DataFrame to ensure correct data types, handles missing values, maps source and target node identifiers, and assigns properties to the edges.

Parameters:
  • df_edges (pd.DataFrame) – DataFrame containing edge data.

  • source_id_col (str) – Name of the column for the source node identifier.

  • source_layer_col (str) – Name of the column for the source node layer.

  • target_id_col (str) – Name of the column for the target node identifier.

  • target_layer_col (str) – Name of the column for the target node layer.

  • property_cols (List[str], optional) – List of additional edge property columns to be added. Defaults to None.

  • drop_na (bool, optional) – Flag to drop rows with missing values in key columns. Defaults to True.

  • fill_na_with (Any, optional) – Value to fill in for missing values if drop_na is False. Defaults to None.

  • string_override (bool, optional) – Flag to force treating property values as strings. Defaults to False.

  • property_types (dict, optional) – Mapping of edge property types. Defaults to None.

Return type:

None

add_vertices_from_dataframe(df_nodes, id_col, layer_col, property_cols=None, drop_na=True, fill_na_with=None, string_override=False, property_types=None)#

Add vertices to the graph from a DataFrame containing node information.

This method processes the DataFrame to ensure correct data types, handles missing values, maps node layers and IDs, and assigns both core and additional properties to the vertices.

Parameters:
  • df_nodes (pd.DataFrame) – DataFrame containing node data.

  • id_col (str) – Name of the column containing node identifiers.

  • layer_col (str) – Name of the column containing node layer information.

  • property_cols (List[str], optional) – List of additional node property columns to be added. Defaults to None.

  • drop_na (bool, optional) – Flag to drop rows with missing id or layer values. Defaults to True.

  • fill_na_with (Any, optional) – Value to fill in for missing values if drop_na is False. Defaults to None.

  • string_override (bool, optional) – Flag to force treating property values as strings. Defaults to False.

  • property_types (dict, optional) – Mapping of node property types. Defaults to None.

Return type:

None

grow_onion(df_nodes, df_edges, node_prop_cols=None, edge_prop_cols=None, drop_na=True, drop_duplicates=True, use_display=False, node_id_col='node_id', node_layer_col='layer', edge_source_id_col='source_id', edge_source_layer_col='source_layer', edge_target_id_col='target_id', edge_target_layer_col='target_layer', vertex_property_types=None, edge_property_types=None)#

Ingest node and edge DataFrames into the graph.

This method validates the input DataFrames, removes duplicates, and optionally displays a snippet of the data. It then calls internal methods to add vertices and edges to the graph.

Parameters:
  • df_nodes (pd.DataFrame) – DataFrame containing node information.

  • df_edges (pd.DataFrame) – DataFrame containing edge information.

  • node_prop_cols (List[str], optional) – List of node property column names. Defaults to [‘node_prop_1’, ‘node_prop_2’].

  • edge_prop_cols (List[str], optional) – List of edge property column names. Defaults to [‘edge_prop_1’, ‘edge_prop_2’].

  • drop_na (bool, optional) – Flag to drop rows with missing key values. Defaults to True.

  • drop_duplicates (bool, optional) – Flag to remove duplicate entries. Defaults to True.

  • use_display (bool, optional) – Flag to display a snippet of data using IPython display if available. Defaults to False.

  • node_id_col (str, optional) – Column name for node identifier. Defaults to ‘node_id’.

  • node_layer_col (str, optional) – Column name for node layer information. Defaults to ‘layer’.

  • edge_source_id_col (str, optional) – Column name for edge source identifier. Defaults to ‘source_id’.

  • edge_source_layer_col (str, optional) – Column name for edge source layer information. Defaults to ‘source_layer’.

  • edge_target_id_col (str, optional) – Column name for edge target identifier. Defaults to ‘target_id’.

  • edge_target_layer_col (str, optional) – Column name for edge target layer information. Defaults to ‘target_layer’.

  • vertex_property_types (dict, optional) – Mapping of vertex property types. Defaults to None.

  • edge_property_types (dict, optional) – Mapping of edge property types. Defaults to None.

Raises:

ValueError – If required columns are missing in the node or edge DataFrames.

Return type:

None

onionnet.core module#

class onionnet.core.OnionNetGraph(directed=True)#

Bases: object

Core graph structure for the OnionNet project.

This class encapsulates a graph_tool.Graph object and provides methods for mapping custom identifiers, layers, and handling categorical properties. It maintains several dictionaries for translating between user-defined identifiers and internal representations.

Parameters:

directed (bool)

graph#

The underlying graph_tool.Graph object.

Type:

Graph

custom_id_to_vertex_index#

Mapping from custom ID tuple (layer, node_id) to vertex index.

Type:

Dict[Tuple[int, int], int]

vertex_index_to_custom_id#

Reverse mapping from vertex index to custom ID tuple.

Type:

Dict[int, Tuple[int, int]]

layer_code_to_name#

Mapping from layer code to layer name.

Type:

Dict[int, str]

layer_name_to_code#

Mapping from layer name to layer code.

Type:

Dict[str, int]

node_id_int_to_str#

Mapping from integer node id to its string representation.

Type:

Dict[int, str]

node_id_str_to_int#

Mapping from string node id to its integer representation.

Type:

Dict[str, int]

vertex_categorical_mappings#

Mappings for vertex categorical properties.

Type:

Dict[str, Dict[str, Any]]

edge_categorical_mappings#

Mappings for edge categorical properties.

Type:

Dict[str, Dict[str, Any]]

onionnet.exporter module#

onionnet.exporter.export_info(g, mode='v', prop_names=None, noisy=False, return_type='pandas')#

Export information from a graph (Graph or GraphView) into a structured format.

This function extracts properties from either vertices or edges based on the specified mode. For vertices, it uses the vertex properties (g.vp) and for edges, it uses edge properties (g.ep) along with source and target vertex identifiers.

Parameters:
  • g (Graph or GraphView) – The graph from which to export data.

  • mode (str, optional) – Export mode: ‘v’ for vertices, ‘e’ for edges. Default is ‘v’.

  • prop_names (list, optional) – A list of property names to include in the export. If None, all properties from g.vp (or g.ep) will be used.

  • noisy (bool, optional) – If True, print details of the exported data during processing. Default is False.

  • return_type (str, optional) –

    The format of the returned data:
    • ”pandas” (default) returns a pandas DataFrame

    • ”list” returns a list of dictionaries

    • ”dict” returns a dictionary keyed by vertex or edge ID

Returns:

The exported graph information in the requested format.

Return type:

pandas.DataFrame, list, or dict

Raises:

ValueError – If the mode is not ‘v’ or ‘e’, or if an invalid return_type is specified.

onionnet.onionnet module#

class onionnet.onionnet.OnionNet(directed=True)#

Bases: object

High-level interface for the OnionNet graph.

This class encapsulates the core graph and provides APIs to build, search, and manage properties of the graph. It uses an underlying OnionNetGraph along with builder, searcher, and property manager components to perform operations on the graph.

Parameters:

directed (bool)

core#

The core graph object.

Type:

OnionNetGraph

builder#

Component for adding nodes and edges to the graph.

Type:

OnionNetBuilder

searcher#

Component for querying and viewing graph subsets.

Type:

OnionNetSearcher

prop_manager#

Component for managing vertex properties.

Type:

OnionNetPropertyManager

_node_map#

Internal cache mapping (layer, node) to vertex index.

Type:

Dict[Tuple[str, str], int]

compose_filters(*args, **kwargs)#

Compose multiple filters to obtain a refined graph view.

Delegates to the searcher’s compose_filters method.

Returns:

A view of the graph after applying composed filters.

Return type:

GraphView

create_bipartite_gv(*args, **kwargs)#

Create a bipartite graph view from the OnionNet graph.

Delegates to the searcher’s create_bipartite_gv method.

Returns:

A bipartite view of the graph.

Return type:

GraphView

create_node_label_property(*args, **kwargs)#

Create a node label property for the graph.

Delegates to the property manager’s create_node_label_property method.

Return type:

None

decode_property_labels_bulk(*args, **kwargs)#

Decode bulk node label properties for the graph.

Delegates to the property manager’s decode_property_labels_bulk method.

Return type:

None

filter_view_by_property(*args, **kwargs)#

Filter the graph view based on vertex or edge properties.

Delegates to the searcher’s filter_view_by_property method.

Returns:

A view of the graph filtered by the specified property criteria.

Return type:

GraphView

get_vertex_by_encoding_tuple(*args, **kwargs)#

Retrieve a vertex based on its encoding tuple.

Delegates to the property manager’s get_vertex_by_encoding_tuple method.

get_vertex_by_name_tuple(*args, **kwargs)#

Retrieve a vertex based on its name tuple.

Delegates to the property manager’s get_vertex_by_name_tuple method.

get_vertex_property(*args, **kwargs)#

Get a property value of a vertex.

Delegates to the property manager’s get_vertex_property method.

grow_onion(*args, **kwargs)#

Grow the OnionNet graph by adding nodes and edges.

Delegates to the builder’s grow_onion method. Resets the internal node_map cache after growing the graph.

Parameters:
  • *args – Positional arguments forwarded to the builder.

  • **kwargs – Keyword arguments forwarded to the builder.

Return type:

None

search(*args, **kwargs)#

Perform a search on the OnionNet graph.

Delegates to the searcher’s search method.

Returns:

A view of the graph based on the search criteria.

Return type:

GraphView

set_vertex_property(*args, **kwargs)#

Set a property value for a vertex.

Delegates to the property manager’s set_vertex_property method.

Return type:

None

view_components(*args, **kwargs)#

View connected components of the OnionNet graph.

Delegates to the searcher’s view_components method.

Returns:

A view of the graph filtered by connected components.

Return type:

GraphView

view_layers(*args, **kwargs)#

View different layers of the OnionNet graph.

Delegates to the searcher’s view_layers method.

Returns:

A view of the graph filtered by layers.

Return type:

GraphView

view_node_properties(*args, **kwargs)#

View all properties of nodes in the graph.

Delegates to the property manager’s view_node_properties method.

view_node_properties_by_names(*args, **kwargs)#

View node properties filtered by specified names.

Delegates to the property manager’s view_node_properties_by_names method.

property g#

Shortcut to access the underlying graph from the OnionNet instance.

Returns:

The core graph contained in the OnionNetGraph.

Return type:

Graph

property node_map: Dict[Tuple[str, str], int]#

Get a mapping from (layer, node) to vertex index.

This property builds and returns a dictionary that maps a tuple of (layer, node name) to the corresponding vertex index in the graph. The mapping is cached internally for efficiency.

Returns:

A dictionary mapping (layer, node) to vertex index.

Return type:

Dict[Tuple[str, str], int]

onionnet.property_manager module#

class onionnet.property_manager.OnionNetPropertyManager(core)#

Bases: object

Parameters:

core (OnionNetGraph)

create_node_label_property(prop_name='node_label')#

Create a new vertex property that serves as a label, combining layer and node identifiers.

The label is formatted as ‘layer:node_id’. If the property already exists, a message is printed.

Parameters:

prop_name (str, optional) – The name of the new label property. Defaults to ‘node_label’.

Return type:

None

Side Effects:

Adds a new vertex property to the graph and prints a confirmation message.

decode_property_labels(encoded_prop_type, encoded_prop_name, new_prop_name=None, mapping_dict=None, default_label='Unknown')#

Create a new property by mapping encoded integer values to human-readable strings.

Uses NumPy vectorized operations to apply the mapping across the property values.

Parameters:
  • encoded_prop_type (str) – ‘v’ for vertex or ‘e’ for edge.

  • encoded_prop_name (str) – Name of the existing encoded property.

  • new_prop_name (str, optional) – Name of the new property. Defaults to f”{encoded_prop_name}_decoded”.

  • mapping_dict (Dict[int, str], optional) – Dictionary mapping integer codes to strings. If not provided, defaults to the core’s categorical mapping for the property.

  • default_label (str) – The label to use if a value is not found in the mapping dictionary.

Return type:

None

Side Effects:

Adds a new property to the graph with human-readable labels and prints a confirmation message.

Raises:
  • ValueError – If the encoded_prop_type is not ‘v’ or ‘e’, or if property conversion fails.

  • KeyError – If the specified encoded property does not exist.

Parameters:
  • encoded_prop_type (str)

  • encoded_prop_name (str)

  • new_prop_name (str)

  • mapping_dict (Dict[int, str])

  • default_label (str)

Return type:

None

decode_property_labels_bulk(df, encoded_prop_type='v')#

Bulk decode categorical properties based on DataFrame columns.

Iterates over each column in the provided DataFrame and applies decode_property_labels to object-type columns, creating a decoded property for each via mapping integer codes to human-readable strings.

Parameters:
  • df (pd.DataFrame) – DataFrame containing columns corresponding to encoded properties.

  • encoded_prop_type (str, optional) – ‘v’ for vertex properties or ‘e’ for edge properties. Defaults to ‘v’.

Return type:

None

Side Effects:

For each object-type column in df, adds a new decoded property to the graph by calling decode_property_labels. Prints a message for non-object-type columns indicating no decoding was performed.

Raises:

KeyError – If decode_property_labels raises a KeyError for a missing property.

Parameters:
Return type:

None

get_vertex_by_encoding_tuple(layer_code, node_id_int)#

Retrieve a vertex from the graph using its encoded identifier tuple.

Parameters:
  • layer_code (int) – The integer code representing the layer.

  • node_id_int (int) – The integer code representing the node identifier.

Returns:

The corresponding vertex object if found; otherwise, None.

Return type:

Vertex

get_vertex_by_name_tuple(layer_name, node_id_str)#

Retrieve a vertex from the graph using its human-readable name tuple.

Parameters:
  • layer_name (str) – The name of the layer.

  • node_id_str (str) – The string representation of the node identifier.

Returns:

The corresponding vertex object if found.

Return type:

Vertex

Raises:

KeyError – If the layer or node ID is not found in the graph’s mappings.

get_vertex_property(layer_code, node_id_int, prop_name)#

Get the value of a specified property for a given vertex.

Parameters:
  • layer_code (int) – The integer code representing the layer.

  • node_id_int (int) – The integer code representing the node identifier.

  • prop_name (str) – The name of the property to retrieve.

Returns:

The value of the property if it exists; otherwise, None.

Return type:

Any

set_vertex_property(layer_code, node_id_int, prop_name, value)#

Set the value of a specified property for a given vertex.

If the property does not already exist, it is created using the inferred type of the provided value.

Parameters:
  • layer_code (int) – The integer code representing the layer.

  • node_id_int (int) – The integer code representing the node identifier.

  • prop_name (str) – The name of the property to set.

  • value (Any) – The value to assign to the property.

Side Effects:

Updates the property map of the graph with the new value.

Notes

If the vertex is not found, a message is printed.

view_node_properties(layer_code, node_id_int)#

View all properties for a specified vertex.

Parameters:
  • layer_code (int) – The integer code representing the layer.

  • node_id_int (int) – The integer code representing the node identifier.

Returns:

A dictionary of property names and their corresponding values for the vertex.

Includes decoded layer and node identifiers.

Return type:

Dict[str, Any]

Side Effects:

If the vertex is not found, prints an error message and returns an empty dictionary.

view_node_properties_by_names(layer_name, node_id_str, verbose=False)#

View properties for a vertex using its human-readable layer and node identifier.

Parameters:
  • layer_name (str) – The name of the layer.

  • node_id_str (str) – The string representation of the node identifier.

  • verbose (bool, optional) – If True, prints the properties. Defaults to False.

Returns:

A dictionary of property names and their corresponding values.

Return type:

Dict[str, Any]

Side Effects:

If verbose is True, prints the properties to the console.

onionnet.searcher module#

class onionnet.searcher.OnionNetSearcher(core)#

Bases: object

Parameters:

core (OnionNetGraph)

compose_filters(filter_funcs, mode='and', type='v', return_prop=False, g=None)#

Create a composite filter from a list of individual filter functions.

Parameters:
  • filter_funcs (list) – A list of functions, each accepting a vertex (or edge) and returning True if it should be kept.

  • mode (str, optional) – Logical combination mode; “and” (default) requires all functions to return True, “or” requires at least one.

  • type (str, optional) – The dimension of filtering; ‘v’ for vertices (default) or ‘e’ for edges.

  • return_prop (bool, optional) – If True, returns a new Boolean property map instead of a GraphView.

  • g (Graph, optional) – The graph to operate on; defaults to self.core.graph.

Returns:

A composite filter represented as a GraphView or a Boolean property map.

Return type:

Union[GraphView, PropertyMap]

Raises:

ValueError – If an invalid mode or type is specified.

compute_on_shortest(source_idx, target_indices, inplace=False, g=None, return_gv=False)#

Compute and return a Boolean vertex property ‘on_shortest’ for vertices that lie on some shortest path from the vertex at source_idx to any vertex in target_indices in an unweighted directed graph.

The function performs the following steps:
  1. Computes forward distances from the source vertex.

  2. Computes reverse distances using a reversed graph view and an artificial source vertex.

  3. Marks vertices that lie on a shortest path if the sum of forward and reverse distances matches a target’s distance.

Parameters:
  • source_idx (int) – The index of the source vertex.

  • target_indices (List[int]) – A list of target vertex indices.

  • inplace (bool, optional) – If False (default), the computation is done on a copy of the graph; if True, the computation is performed in-place on the original graph.

  • g (Graph, optional) – An optional graph to operate on; defaults to self.core.graph if not provided.

  • return_gv (bool, optional) – If True, returns a GraphView filtered by the computed property; otherwise, returns the Boolean property map.

Returns:

A GraphView if return_gv is True, or the Boolean property map otherwise.

Return type:

Union[GraphView, PropertyMap]

Raises:

ValueError – If the source index or any target index is invalid.

create_bipartite_gv(layer1, layer2, prop_name='layer_decoded')#

Create a bipartite GraphView that retains vertices whose specified property matches either layer1 or layer2, and includes only edges connecting vertices between these two layers.

Parameters:
  • layer1 (str) – The first layer value (e.g., ‘swisslipids’).

  • layer2 (str) – The second layer value (e.g., ‘sl_chebi’).

  • prop_name (str, optional) – The vertex property used for filtering (default is ‘layer_decoded’).

Returns:

A filtered view of the graph containing only vertices in the specified layers and edges connecting vertices from different layers. Vertices without any incident edges in the filtered view are removed.

Return type:

GraphView

filter_view_by_property(prop_name, target_value, comparison='==', dim='v', prune_isolated=False)#

Filter the graph based on a specified vertex or edge property and return a GraphView.

Parameters:
  • prop_name (str) – The property name to filter by.

  • target_value (Any) – The value or set of values to compare against.

  • comparison (str, optional) – Comparison operator (default “==”). Options: “==”, “!=”, “<”, “>”, “<=”, “>=”.

  • dim (str, optional) – Dimension to filter on; ‘v’ for vertices (default) or ‘e’ for edges.

  • prune_isolated (bool, optional) – If True, further filters the view to retain only vertices with at least one incident edge.

Returns:

A filtered view of the graph based on the property filter.

Return type:

GraphView

Raises:

ValueError – If the property does not exist or an invalid dimension is provided.

search(start_node_idx=0, max_dist=5, direction='downstream', node_text_prop='node_label', show_plot=True, include_upstream_children=False, verbosity=False, g=None, **kwargs)#

Perform a search on the graph to extract a subgraph within a specified distance from a starting node.

The search can be conducted in ‘downstream’, ‘upstream’, or bidirectional (‘bi’) mode. It computes the shortest distances from the starting vertex and returns a GraphView containing vertices within the specified maximum distance. Optionally, the subgraph can be plotted.

Parameters:
  • start_node_idx (int, optional) – The index of the starting vertex (default is 0).

  • max_dist (int, optional) – Maximum distance (in hops) from the starting vertex (default is 5).

  • direction (str, optional) – Direction of search; ‘downstream’, ‘upstream’, or ‘bi’ for bidirectional (default is ‘downstream’).

  • node_text_prop (str, optional) – Vertex property to use for node labels in the plot (default is ‘node_label’).

  • show_plot (bool, optional) – If True, displays a plot of the filtered subgraph (default is True).

  • include_upstream_children (bool, optional) – For bidirectional search, if True, include additional upstream children (default is False).

  • verbosity (bool, optional) – If True, prints detailed information during the search process (default is False).

  • g (Graph, optional) – An optional graph to operate on; defaults to self.core.graph if not provided.

  • **kwargs – Additional keyword arguments passed to graph_draw for plotting.

Returns:

A filtered view of the graph containing vertices within the specified distance from the start vertex.

Return type:

GraphView

Raises:

ValueError – If the starting vertex index is invalid or if an invalid search direction is specified.

view_components(size_threshold, connectivity='strong', g=None)#

Create a GraphView that shows connected components of the graph with a minimum size.

Parameters:
  • size_threshold (int) – The minimum number of vertices a component must have to be included.

  • connectivity (str, optional) – ‘strong’ for strongly connected components, otherwise weakly connected (default is “strong”).

  • g (Graph, optional) – The graph to operate on; defaults to self.core.graph.

Returns:

A view of the graph showing only components that meet the size threshold.

Return type:

GraphView

view_layers(layer_names, return_filter=False, copy_gv=False)#

Generate a GraphView filtered by the specified layer names.

Parameters:
  • layer_names (Union[List[str], str]) – A single layer name or a list of layer names to filter vertices by.

  • return_filter (bool, optional) – If True, returns the Boolean vertex property used for filtering instead of a GraphView.

  • copy_gv (bool, optional) – If True, returns a new Graph object constructed from the GraphView.

Returns:

The filtered GraphView or Boolean property map based on the layer filter.

Return type:

Union[GraphView, PropertyMap]

Raises:

ValueError – If any specified layer name does not exist.

onionnet.utils module#

onionnet.utils.infer_property_type(value)#

Infer the property type based on a pandas Series or a single sample value.

This function inspects the input value to determine its type. If the value is a pandas Series, it uses the Series dtype to infer the type and returns:

  • ‘int’ for integer types,

  • ‘float’ for floating-point types,

  • ‘bool’ for boolean types,

  • ‘string’ for object or other types.

For individual sample values, the function checks the type using isinstance and returns the corresponding string.

Parameters:

value – A pandas Series or a single sample value (int, float, bool, or str).

Returns:

A string representing the inferred property type. Possible return values include ‘int’, ‘float’, ‘bool’, ‘string’, or ‘object’.

Return type:

str

onionnet.utils.map_categorical_property(prop_name, values, mapping=None)#

Map categorical property values to unique integer codes.

This function converts an iterable of categorical values into a NumPy array of integer codes. Each unique value is assigned a unique integer. If an initial mapping is provided, it will be used as the starting point; otherwise, a new mapping is created. The function returns both the array of integer codes and the mapping dictionary.

Parameters:
  • prop_name (str) – The name of the property being mapped (used for reference or debugging).

  • values (iterable) – An array-like collection of categorical values to map.

  • mapping (Dict[str, int], optional) – An existing dictionary mapping categorical values to integer codes. Defaults to None.

Returns:

A tuple containing:
  • mapped_values (np.ndarray): A NumPy array of integer codes corresponding to each value in ‘values’.

  • mapping (Dict[str, int]): The updated dictionary mapping each unique categorical value to its integer code.

Return type:

tuple

onionnet.visualisation module#

onionnet.visualisation.add_halo_to_node(g, node, halo_color=(1.0, 1.0, 0.0, 0.5), halo_size_factor=1.5)#

Add a halo to a specific node while styling the graph.

Parameters:#

  • g (Graph): The graph object.

  • node (Vertex): The specific vertex requiring a halo.

  • halo_color (tuple): RGBA color for the halo.

  • halo_size_factor (float): Size of the halo relative to the node size.

Returns:#

: - result (dict): A dictionary containing:

  • ‘v_halo’ (PropertyMap): Halo property map (only for the specific node).

  • ‘v_halo_color’ (PropertyMap): Halo colour as a property map (only for the specific node with halo).

onionnet.visualisation.bipartite_ordered_layout(g, left_val, right_val, layer_prop='layer_decoded', sort_left_by=<function <lambda>>, vertical_spacing=30.0, horizontal_spacing=1.0)#
Arrange a bipartite graph so edges are as horizontal as possible:
  1. Identify the left set (layer == left_val) and the right set (layer == right_val).

  2. Sort the left set by a given key function (default: vertex id).

  3. Sort each node on the right by the average index of its neighbors on the left.

  4. Assign x=0 for the left side, x=horizontal_spacing for the right side. Multiply the y-index by vertical_spacing for each side.

Parameters:
  • g (graph_tool.Graph or GraphView) – The bipartite graph.

  • left_val (str) – The property value used for the left side. E.g. ‘layer_1’

  • right_val (str) – The property value used for the right side. E.g. ‘layer_2’

  • layer_prop (str, optional) – Vertex property name that stores the layer. Default: ‘layer_decoded’.

  • sort_left_by (callable, optional) – A function used to sort the left side’s vertices. Default: sorts by vertex ID.

  • vertical_spacing (float, optional) – Multiplier for vertical distances. A larger value spreads nodes further vertically. Default is 30.0.

  • horizontal_spacing (float, optional) – The x distance between the left and right columns. Default is 1.0.

Returns:

pos – A 2D coordinate property map for graph-tool, with x=0 or x=horizontal_spacing for each side and y determined by the sorted index times vertical_spacing.

Return type:

VertexPropertyMap

onionnet.visualisation.color_edges(g, prop_name, method='categorical', generate_legend=False, custom_colormap=None, custom_color_dict=None, zero_centred=False)#

Assign colors to edges in a graph.

Parameters:#

g (Graph): The graph object where edges are styled. prop_name (str): The name of the edge property used to determine colors. method (str):

‘categorical’: assigns distinct colors for each unique category in the property. ‘continuous’: uses a color scale. ‘boolean’: uses red if the property is True, grey if False.

generate_legend (bool): If True, generates a legend dictionary mapping categories to colors. custom_colormap (Colormap or None): A custom matplotlib colormap for continuous values. custom_color_dict (dict or None): A user-defined dictionary mapping property values to colors. zero_centred (bool): If True (and method is ‘continuous’), adjusts the normalization range so that

zero is centered. Defaults to False.

Returns:#

: dict: A dictionary containing:

  • ‘e_color’ (PropertyMap): An edge property map with RGBA color values.

  • ‘legend_edge_color’ (dict or None): A dictionary mapping categories to colors if generate_legend is True.

onionnet.visualisation.color_nodes(g, prop_name, method='categorical', generate_legend=False, custom_colormap=None, custom_color_dict=None, zero_centred=False, transparency=1.0)#

Assign colors to nodes in a graph.

Parameters:#

  • g (Graph): The graph object where nodes are styled.

  • prop_name (str): The name of the vertex property used to determine colors.

  • method (str):

    ‘categorical’: assigns distinct colors for each unique category in the property. ‘continuous’ : uses a color scale. ‘boolean’ : uses red if the property is True, grey if False.

  • generate_legend (bool): If True, generates a legend dictionary mapping categories to colors.

  • custom_colormap (Colormap or None): A custom matplotlib colormap for continuous values.

  • custom_color_dict (dict or None): A user-defined dictionary mapping property values to colors.

  • zero_centered (bool): If True (and method is ‘continuous’), adjusts the normalization range so that

    zero is centered (i.e. using symmetric bounds [-abs(max_val), abs(max_val)]). Defaults to False.

  • transparency (float): Transparency level for the colors (0.0 to 1.0). Default is 1.0 (fully opaque).

Returns:#

: - result (dict): A dictionary containing:

  • ‘v_color’ (PropertyMap): A vertex property map with RGBA color values.

  • ‘legend’ (dict): A dictionary mapping categories to colors (if generate_legend=True).

onionnet.visualisation.create_node_labels(g, property_map)#

Creates a vertex property for node labels from potentially nested properties.

Return type:

PropertyMap

Parameters:
  • g (Graph)

  • property_map (PropertyMap)

Parameters:#

ggraph_tool.Graph

The graph containing the nodes.

property_mapgraph_tool.PropertyMap

A property map containing the nested properties for each node.

Returns:#

: vertex_labels : graph_tool.PropertyMap

A string property map with flattened and unique properties as node labels.

onionnet.visualisation.flatten_properties(nested_properties)#

Utility function to flatten a list of nested properties into a single list. Assumes that properties may be nested within sublists.

Return type:

List[str]

Parameters:

nested_properties (List[Any])

Parameters:#

nested_propertieslist

The list of potentially nested properties to be flattened.

Returns:#

: List[str]

A flattened list of properties, with duplicates removed.

onionnet.visualisation.get_legend(source, prop=None, ordered_cats=None, verbose=False, mode=None, custom_cmap=None, title=None, save_filename=None)#

Generates a legend for a graph coloring.

Parameters:#

source: Either a graph (with vertex or edge properties) or a legend dictionary mapping categories to colors. prop: If source is a graph, the property name to extract values from (vertex or edge property). ordered_cats: Optional list specifying the order of categories in the legend (for categorical legends). verbose: If True, prints debug information. mode: Optional, ‘categorical’ or ‘continuous’. If None, the function will infer the mode from the property type. custom_cmap: A custom matplotlib colormap to use for continuous legends. Defaults to viridis if not provided.

Behavior:#

  • If source is a dictionary: * If it contains keys ‘min_col’ and ‘max_col’, it is treated as a continuous legend dictionary and a colorbar is displayed.

    • Otherwise, it is treated as a categorical mapping from categories to colors.

  • If source is a graph object, the function extracts the property values from source.vp[prop] or source.ep[prop].

    If the property values are numeric (or mode is set to ‘continuous’), a continuous colorbar is displayed.

    Otherwise, a categorical legend is constructed using a default colormap (tab10).

Parameters:
  • title (str)

  • save_filename (str)

onionnet.visualisation.layout_by_layer(g, layer_prop_name='layer_decoded', spacing=50, epsilon=0.01)#

Create a 2D layout that places nodes in vertical columns based on their layer. Vertices in each layer are spaced out by ‘spacing’ units. If a layer has only one vertex, a small random offset (epsilon) is added to avoid a zero spread.

onionnet.visualisation.load_or_compute_layout(g, filename, override=False, inject=None)#

Loads vertex layout coordinates from a TSV file if it exists (and override is False), or computes/injects them and saves them to the file.

The TSV file is expected to have the following key columns:
  • Either: layer_hash and node_id_hash (primary keys)

  • Or: v_int (if layer and node hash are not available)

  • Additionally, x and y for coordinates.

Parameters:
  • g (graph_tool.Graph) – The graph for which the layout is needed.

  • filename (str) – The path to the TSV file where layout coordinates are stored or should be saved.

  • override (bool, optional) – If True, recompute/inject the layout even if the file already exists and update the file. Default is False.

  • inject (None, callable, or a precomputed layout, optional) – If provided, use this layout instead of computing via sfdp_layout. If callable, it should accept the graph g and return a layout (vertex property map). Otherwise, it should be a layout that maps vertices to [x, y] coordinates.

Returns:

pos – A vertex property map containing the 2D coordinates for each vertex.

Return type:

graph_tool.VertexPropertyMap

onionnet.visualisation.prop_to_size(g, prop, mi=1, ma=8, power=1, transform_func=None, mode='v')#

Scales a property to a specified size range with an optional power transformation and custom vectorized transformation.

Parameters:#

ggraph_tool.Graph

The graph object.

proparray-like or PropertyMap

The property values to scale. Can be a list, numpy array, or a graph-tool property map (g.vp or g.ep).

mifloat

Minimum size.

mafloat

Maximum size.

powerfloat

Power to apply for scaling.

transform_funccallable, optional

A function to apply to the property values before scaling. This function should support vectorized operations. If it doesn’t, np.vectorize will be used as a fallback.

modestr, optional

Specifies whether the property is a vertex property (‘v’) or an edge property (‘e’). Defaults to ‘v’.

Returns:#

: size_prop : graph_tool.PropertyMap

A property map with the scaled sizes, either a vertex or edge property map based on mode.

onionnet.visualisation.set_node_sizes_and_text_by_depth(g, root, max_size=20, min_size=5, max_text_size=15, min_text_size=8)#

Set node sizes and text sizes based on their depth in the tree.

Parameters: - g (Graph): The graph object. - root (Vertex): The root vertex from which to calculate depths. - max_size (int): Maximum size for inner nodes (closer to the root). - min_size (int): Minimum size for outer nodes (further from the root). - max_text_size (int): Maximum text size for inner nodes. - min_text_size (int): Minimum text size for outer nodes.

Returns: - v_size (PropertyMap): A vertex property map with sizes based on depth. - v_text_size (PropertyMap): A vertex property map for text sizes based on depth.

onionnet.visualisation.shape_nodes(g, prop_name, shape_method=None, generate_legend=False, custom_shape_dict=None)#

Assign shapes to nodes in a graph.

Parameters:#

  • g (Graph): The graph object where nodes are styled.

  • prop_name (str): The name of the vertex property used to determine shapes.

  • shape_method (str or None): If specified, assigns vertex shapes based on a property or method.

  • generate_legend (bool): If True, generates a legend dictionary mapping categories to shapes.

  • custom_shape_dict (dict or None): A user-defined dictionary mapping property values to shapes.

Returns:#

: - result (dict): A dictionary containing:

  • ‘v_shape’ (PropertyMap): A vertex property map with shape values.

  • ‘legend’ (dict): A dictionary mapping categories to shapes (if generate_legend=True).

Module contents#

class onionnet.OnionNet(directed=True)#

Bases: object

High-level interface for the OnionNet graph.

This class encapsulates the core graph and provides APIs to build, search, and manage properties of the graph. It uses an underlying OnionNetGraph along with builder, searcher, and property manager components to perform operations on the graph.

Parameters:

directed (bool)

core#

The core graph object.

Type:

OnionNetGraph

builder#

Component for adding nodes and edges to the graph.

Type:

OnionNetBuilder

searcher#

Component for querying and viewing graph subsets.

Type:

OnionNetSearcher

prop_manager#

Component for managing vertex properties.

Type:

OnionNetPropertyManager

_node_map#

Internal cache mapping (layer, node) to vertex index.

Type:

Dict[Tuple[str, str], int]

compose_filters(*args, **kwargs)#

Compose multiple filters to obtain a refined graph view.

Delegates to the searcher’s compose_filters method.

Returns:

A view of the graph after applying composed filters.

Return type:

GraphView

create_bipartite_gv(*args, **kwargs)#

Create a bipartite graph view from the OnionNet graph.

Delegates to the searcher’s create_bipartite_gv method.

Returns:

A bipartite view of the graph.

Return type:

GraphView

create_node_label_property(*args, **kwargs)#

Create a node label property for the graph.

Delegates to the property manager’s create_node_label_property method.

Return type:

None

decode_property_labels_bulk(*args, **kwargs)#

Decode bulk node label properties for the graph.

Delegates to the property manager’s decode_property_labels_bulk method.

Return type:

None

filter_view_by_property(*args, **kwargs)#

Filter the graph view based on vertex or edge properties.

Delegates to the searcher’s filter_view_by_property method.

Returns:

A view of the graph filtered by the specified property criteria.

Return type:

GraphView

get_vertex_by_encoding_tuple(*args, **kwargs)#

Retrieve a vertex based on its encoding tuple.

Delegates to the property manager’s get_vertex_by_encoding_tuple method.

get_vertex_by_name_tuple(*args, **kwargs)#

Retrieve a vertex based on its name tuple.

Delegates to the property manager’s get_vertex_by_name_tuple method.

get_vertex_property(*args, **kwargs)#

Get a property value of a vertex.

Delegates to the property manager’s get_vertex_property method.

grow_onion(*args, **kwargs)#

Grow the OnionNet graph by adding nodes and edges.

Delegates to the builder’s grow_onion method. Resets the internal node_map cache after growing the graph.

Parameters:
  • *args – Positional arguments forwarded to the builder.

  • **kwargs – Keyword arguments forwarded to the builder.

Return type:

None

search(*args, **kwargs)#

Perform a search on the OnionNet graph.

Delegates to the searcher’s search method.

Returns:

A view of the graph based on the search criteria.

Return type:

GraphView

set_vertex_property(*args, **kwargs)#

Set a property value for a vertex.

Delegates to the property manager’s set_vertex_property method.

Return type:

None

view_components(*args, **kwargs)#

View connected components of the OnionNet graph.

Delegates to the searcher’s view_components method.

Returns:

A view of the graph filtered by connected components.

Return type:

GraphView

view_layers(*args, **kwargs)#

View different layers of the OnionNet graph.

Delegates to the searcher’s view_layers method.

Returns:

A view of the graph filtered by layers.

Return type:

GraphView

view_node_properties(*args, **kwargs)#

View all properties of nodes in the graph.

Delegates to the property manager’s view_node_properties method.

view_node_properties_by_names(*args, **kwargs)#

View node properties filtered by specified names.

Delegates to the property manager’s view_node_properties_by_names method.

property g#

Shortcut to access the underlying graph from the OnionNet instance.

Returns:

The core graph contained in the OnionNetGraph.

Return type:

Graph

property node_map: Dict[Tuple[str, str], int]#

Get a mapping from (layer, node) to vertex index.

This property builds and returns a dictionary that maps a tuple of (layer, node name) to the corresponding vertex index in the graph. The mapping is cached internally for efficiency.

Returns:

A dictionary mapping (layer, node) to vertex index.

Return type:

Dict[Tuple[str, str], int]