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, drop_duplicates=True, string_override=False, property_types=None, consider_props_in_duplicate=False)#

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) – key columns.

  • source_layer_col (str) – key columns.

  • target_id_col (str) – key columns.

  • target_layer_col (str) – key columns.

  • property_cols (List[str], optional) – List of edge property columns.

  • drop_na (bool) – Drop rows with missing keys if True; else error on NA.

  • drop_duplicates (bool) – Drop duplicate edge pairs (source,layer,target,layer rows) if True, including double self loops.

  • string_override (bool) – Treat all props as categorical.

  • property_types (dict) – Explicit types for properties.

  • consider_props_in_duplicate (bool) – If True, duplicates are defined by endpoints and the listed property columns (so two nodes could be from A1->A2, but with different properties or property values), otherwise only by endpoints.

Return type:

None

add_vertices_from_dataframe(df_nodes, id_col, layer_col, property_cols=None, drop_na=True, drop_duplicates=True, 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.

  • drop_na (bool) – Drop rows with missing id/layer if True; else error on NA.

  • drop_duplicates (bool) – Drop duplicate (id,layer) rows if True.

  • string_override (bool) – Treat all props as categorical if True.

  • property_types (dict) – Explicit types for properties.

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, verbose=True)#

Ingest node and edge DataFrames into the graph.

This method validates the input DataFrames, and optionally displays a snippet of the data. By default, it then performs NA-dropping, duplicate removal, filters invalid edges, and finally adds vertices and edges to the graph. A summary of counts at each step is recorded and can be printed.

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

  • edge_prop_cols (List[str], optional) – List of edge property column names. Defaults to None.

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

  • drop_duplicates (bool, optional) – Flag to remove duplicate entries. Note this applies to _both_ nodes and edges. Defaults to False.

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

  • verbose (bool, optional) – Prints summary of graph creation. Defaults to True.

Raises:

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

Return type:

None

summary()#
Return type:

str

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.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_edges_between_categories(*args, **kwargs)#
High-level convenience: filter only those edges whose

source_layer==… AND target_layer==…,

and then prune isolated vertices.

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_category_code(*args, **kwargs)#

Look up the integer code for a categorical property value so you can build GraphView filters without digging into internals.

Return type:

int

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', g=None)#

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.

  • g (Graph)

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)

  • g (Graph)

Return type:

None

decode_property_labels_bulk(df, encoded_prop_type='v', g=None)#

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

  • g (Graph)

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_category_code(prop_name, category_label, dim='v')#

Look up the integer code for a categorical property value. This can then be used for lamda vertex (dim=’v’) or edge (dim=’e’) filtering.

Parameters:
  • prop_name (str) – The name of the property (vertex or edge) that is categorical.

  • category_label (str) – The human-readable category label whose integer code you want.

  • dim (str, optional) – ‘v’ for a vertex property map, ‘e’ for an edge property map.

Returns:

The integer code for that category, or None if not present.

Return type:

int

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, targets, return_gv=True, inplace=True, g=None, directed=True)#

Mark nodes that lie on any shortest path from a single source to one or more targets.

This is a fast, allocation-light routine for large (unweighted) graphs. It does not permanently attach properties to your graph; it only creates a temporary boolean on_sp (on-shortest-path) property and, by default, returns a GraphView filtered by it.

Behavior by mode#

If directed=True (default):
  • Run 1 forward BFS from the source on G

  • Run 1 reverse-view BFS per target on reversed(G)

  • A vertex v is on-shortest-path iff

    forward_dist[v] + reverse_dist[v] == forward_dist[target]

If directed=False (treat as undirected):
  • Run 1 BFS from the source with directed=False

  • Run 1 BFS from each target with directed=False (no reverse view)

  • Combine target BFS results by elementwise min

Method (high level)#

1) Coerce inputs to integer vertex indices (accepts ints, Vertices, or (layer_name, node_id_str) tuples via PropertyManager). 2) Compute forward distances from source. 3) Compute reverse/other-side distances from targets as described above. 4) Compute the set of required path lengths to each target. 5) Mark v as on-shortest if forward[v] + reverse[v] matches one of those lengths. 6) Return a GraphView over those vertices (or the raw boolean property).

type source:

param source:

Source vertex, either by integer index, a graph-tool Vertex, or a (layer_name, node_id_str) pair.

type source:

int | Vertex | tuple[str, str]

type targets:

param targets:

One or more targets in the same accepted formats as source.

type targets:

list | tuple

type return_gv:

bool

param return_gv:

If True, return a GraphView filtered to on-shortest vertices. If False, return the boolean vertex PropertyMap instead.

type return_gv:

bool, default True

type inplace:

bool

param inplace:

If False, operate on a copy of g/core.graph before building the view. (Useful if you plan to attach the property.)

type inplace:

bool, default True

type g:

Graph

param g:

Optional graph to use instead of self.core.graph.

type g:

Graph | None

type directed:

bool

param directed:

Whether to treat the graph as directed. If False, run undirected BFS.

type directed:

bool, default True

returns:
  • GraphView | PropertyMap – Filtered view (default) or the boolean vertex property.

  • Complexity

  • ———-

  • O((V + E) + T * (V + E)) in the worst case, where T = number of targets.

  • With a single target, it’s ~two BFS passes → O(V + E).

Examples

# with layer/node labels >>> searcher.compute_on_shortest( … source=(“layer1”, “nodeA”), … targets=[(“layer2”, “nodeB”), (“layer3”, “nodeC”)], … )

# with integer indices, undirected >>> searcher.compute_on_shortest(42, [43, 44], directed=False)

Parameters:
create_bipartite_gv(layer1, layer2, prop_name='layer_decoded')#
Return type:

GraphView

Parameters:
filter_edges(predicate, return_view=True)#

Keep only those edges for which predicate(e) is True, then prune any isolated vertices.

Parameters:
  • predicate (Callable) – A function taking a graph-tool Edge and returning True to keep it.

  • return_view (bool) – If True, returns a GraphView; if False, returns the raw edge‐bool PropertyMap.

Return type:

GraphView or PropertyMap

filter_edges_between_categories(source_label, target_label, mode='forward')#

Filter edges by their endpoint layers and return a pruned GraphView.

This method selects edges whose source vertex’s layer matches source_label and whose target vertex’s layer matches target_label, according to the integer layer codes stored in the graph’s ‘layer_hash’ vertex property. You can choose one of three modes:

  • forward: keep edges where source→target

  • reverse: keep edges where target→source

  • both: keep edges in either direction

After filtering, any vertices that become isolated (no remaining incident edges) are automatically pruned.

Vectorized to: - look up the integer codes for source_label and target_label - build a NumPy mask of edges whose (src_layer, tgt_layer) matches

one of the allowed pairs for forward/reverse/both

  • return a pruned GraphView

Parameters:
  • source_label (str) – Human-readable name of the layer for edge sources. Must exist in self.core.layer_name_to_code, or a KeyError is raised.

  • target_label (str) – Human-readable name of the layer for edge targets. Must exist in self.core.layer_name_to_code, or a KeyError is raised.

  • mode ({'forward','reverse','both'}, optional) – Which direction(s) to keep: - ‘forward’: source→target only (default) - ‘reverse’: target→source only - ‘both’: both directions

Returns:

A filtered view of the underlying graph containing only the selected edges, with any isolated vertices removed.

Return type:

GraphView

Raises:
  • KeyError – If source_label or target_label is not found in the layer-name mapping.

  • ValueError – If mode is not one of ‘forward’, ‘reverse’, or ‘both’.

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’, bidirectional (‘bi’), or non-directed (‘any’) 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’, ‘bi’ for bidirectional, or ‘any’ for non-directed (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.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.add_halos_to_nodes(g, nodes, colors=None, default_color=(1.0, 1.0, 0.0, 0.6), prop_name_halo='v_halo', prop_name_color='v_halo_color')#

Create per-vertex halo + halo-color property maps for one or more nodes.

Parameters:
  • g (Graph or GraphView) – The graph you will draw.

  • nodes (sequence of Vertex or int) – Vertices to highlight. (If you pass ints, they are treated as vertex indices.)

  • colors (sequence of RGBA tuples, optional) – Per-node halo colors; if fewer than nodes, default_color is used for the rest.

  • default_color (tuple) – Fallback RGBA.

  • prop_name_halo (str) – Name to assign the boolean halo map into g.vp.

  • prop_name_color (str) – Name to assign the vector<double> color map into g.vp.

Returns:

{“v_halo”: halo_bool_map, “v_halo_color”: halo_color_map}

Return type:

dict

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 graph coloring or shaping.

Parameters:
  • source (dict or graph) –

    • If dict:
      • Continuous color dict: must contain ‘min_col’ and ‘max_col’ (and min_val/max_val).

      • Categorical color dict: {category -> color (rgba/hex/tuple)}.

      • Categorical shape dict: {category -> shape_name}, e.g. ‘circle’,’triangle’,’square’,’pentagon’, etc.

    • If graph: a graph-tool Graph or GraphView that has vp/ep[prop].

  • prop (str or None) – Property name if source is a graph. Ignored for dict source.

  • ordered_cats (list or None) – Custom order of categories in the legend.

  • verbose (bool) – Print debug info.

  • mode ({'categorical', 'continuous', None}) – When source is a graph, infer if None. Ignored for dict source.

  • custom_cmap (matplotlib colormap or None) – Colormap for continuous legends.

  • title (str or None) – Legend title.

  • save_filename (str or None) – If provided, saves an SVG to f”{save_filename}.svg”.

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)#
Load or compute a 2D layout for g, keyed by either:
  1. (‘layer_decoded’,’node_id_decoded’) [preferred human-readable]

  2. (‘layer_hash’,’node_id_hash’) [encoded integer hashes]

  3. ‘v_int’ [fallback to vertex index IF neither pair exists]

Robust key handling:
  • Decoded keys are coerced to str on both TSV and graph sides.

  • Hash keys are coerced to int on both sides (tolerant of “123.0”).

  • v_int keys use int(vertex_index) and are used only when neither key-pair exists.

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

onionnet.analytics module#

onionnet.analytics.layer_stats(df_nodes=None, df_edges=None, *, core=None, node_layer_col='layer', source_layer_col='source_layer', target_layer_col='target_layer', print_tables=True)#

Compute quick layer summaries.

You can pass DataFrames (fast, no need to scan the graph) OR, if you already built the graph and kept layer props on vertices/edges, pass core and it will derive the same tables.

Return type:

Tuple[pd.DataFrame, Optional[int], Optional[pd.DataFrame]]

Returns:

  • nodes_by_layer (DataFrame with a single ‘count’ column (index = layer))

  • interlayer_edge_count (int or None)

  • edges_by_pair (DataFrame with a single ‘edges’ column)

Parameters:
  • df_nodes (Optional[pd.DataFrame])

  • df_edges (Optional[pd.DataFrame])

  • core (Optional['OnionNetGraph'])

  • node_layer_col (str)

  • source_layer_col (str)

  • target_layer_col (str)

  • print_tables (bool)

onionnet.analytics.plot_layer_metagraph(edges_by_pair, nodes_by_layer=None, *, node_scaler='log', edge_scaler='log', node_size_range=(10, 60), edge_width_range=(0.5, 8.0), node_text_size_range=(10, 16), edge_text_size_range=(8, 14), show_edge_counts=False, show_node_counts=False, node_label_fmt='{layer}\\n(n={count})', node_text_position=-1, pad_label_string=False, use_monospace_font=False, vertex_font=None, edge_font=None, family_colors=None, family_extractor=None, layout='sfdp', show_labels=True, output_size=(900, 700), return_graph=False, pos=None)#

Draw a meta-graph whose vertices are layers and edges count cross-layer edges.

What it shows#

  • Vertex size ∝ per-layer node count (uniform if nodes_by_layer=None).

  • Edge width ∝ edges between layer pairs.

  • Optional labels:
    • show_node_counts=True: include per-layer count in the vertex label.

    • show_edge_counts=True: draw the edge count as a label on edges.

Scaling & ranges#

  • Counts are transformed by node_scaler / edge_scaler (‘log’ or ‘linear’).

  • Clamped to node_size_range, edge_width_range.

  • Text sizes are independently clamped via node_text_size_range, edge_text_size_range.

type edges_by_pair:

pd.DataFrame

param edges_by_pair:

MultiIndex (source_layer, target_layer) with an ‘edges’ column.

type edges_by_pair:

DataFrame

type nodes_by_layer:

Optional[pd.DataFrame]

param nodes_by_layer:

Optional per-layer node counts (column ‘count’).

type nodes_by_layer:

DataFrame or None

type node_text_position:

Union[int, float]

param node_text_position:

-1 to center text inside node; otherwise angle (radians) relative to node.

type node_text_position:

float|int

type family_colors:

Optional[Dict[str, Tuple[float, float, float, float]]]

param family_colors:

Map family→RGBA; overrides auto palette. Families are derived by family_extractor (or a simple prefix heuristic if None).

type family_colors:

dict or None

type family_extractor:

Optional[Callable[[str], str]]

param family_extractor:

Given a layer name → family string (used for coloring).

type family_extractor:

callable or None

type pos:

param pos:

Reuse a precomputed layout; if None, compute one.

type pos:

VertexPropertyMap or None

rtype:

None or (Graph, PropertyMap)

Parameters:
  • edges_by_pair (pd.DataFrame)

  • nodes_by_layer (Optional[pd.DataFrame])

  • node_scaler (str)

  • edge_scaler (str)

  • node_size_range (Tuple[float, float])

  • edge_width_range (Tuple[float, float])

  • node_text_size_range (Tuple[float, float])

  • edge_text_size_range (Tuple[float, float])

  • show_edge_counts (bool)

  • show_node_counts (bool)

  • node_label_fmt (str)

  • node_text_position (Union[int, float])

  • pad_label_string (bool)

  • use_monospace_font (bool)

  • vertex_font (Optional[str])

  • edge_font (Optional[str])

  • family_colors (Optional[Dict[str, Tuple[float, float, float, float]]])

  • family_extractor (Optional[Callable[[str], str]])

  • layout (str)

  • show_labels (bool)

  • output_size (Tuple[int, int])

  • return_graph (bool)

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

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_edges_between_categories(*args, **kwargs)#
High-level convenience: filter only those edges whose

source_layer==… AND target_layer==…,

and then prune isolated vertices.

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_category_code(*args, **kwargs)#

Look up the integer code for a categorical property value so you can build GraphView filters without digging into internals.

Return type:

int

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]