napistu.network.ng_core

Core graph class for molecular network analysis.

Classes

NapistuGraph

Core graph class for molecular network analysis.

Classes

NapistuGraph(*args, **kwargs)

NapistuGraph - Molecular Network Analysis Graph.

class napistu.network.ng_core.NapistuGraph(*args, **kwargs)

Bases: Graph

NapistuGraph - Molecular Network Analysis Graph.

A subclass of igraph.Graph with additional functionality for molecular network analysis. This class extends igraph.Graph with domain-specific methods and metadata tracking for biological pathway and molecular interaction networks. All standard igraph methods are available, plus additional functionality for edge reversal, weighting, and metadata management.

is_reversed

Whether the graph edges have been reversed from their original direction

Type:

bool

wiring_approach

Type of graph (e.g., ‘bipartite’, ‘regulatory’, ‘surrogate’)

Type:

str or None

weighting_strategy

Strategy used for edge weighting (e.g., ‘topology’, ‘mixed’)

Type:

str or None

weight_by

List of attributes used for edge weighting

Type:

list[str] or None

Public Methods (alphabetical)
----------------------------
add_degree_attributes(inplace=True)

Add degree-based attributes to vertices and edges.

add_edge_data(sbml_dfs, side_loaded_attributes, mode='fresh', overwrite=False, inplace=True)

Add edge data from SBML_dfs to the graph.

add_topology_weights(base_score=2, protein_multiplier=1, metabolite_multiplier=3, unknown_multiplier=10, scale_multiplier_by_meandegree=True, inplace=True)

Add topology-based weights to graph edges.

add_sbml_dfs_summaries(sbml_dfs, summary_types=VALID_VERTEX_SBML_DFS_SUMMARIES, priority_pathways=DEFAULT_PRIORITIZED_PATHWAYS, stratify_by_bqb=True, characteristic_only=False, dogmatic=False, add_name_prefixes=False, binarize=True, inplace=True)

Add vertex summaries from SBML_dfs to the graph vertices.

add_vertex_data(sbml_dfs, side_loaded_attributes, mode='fresh', overwrite=False, inplace=True)

Add vertex data from SBML_dfs to the graph.

copy

Create a deep copy of the NapistuGraph.

deduplicate_edges(verbose=False)

Deduplicate edges with the same FROM -> TO pair, keeping only the first occurrence.

from_igraph(graph, \*\*metadata)

Create a NapistuGraph from an existing igraph.Graph.

from_pickle(path)

Load a NapistuGraph from a pickle file.

get_edge_dataframe

Return graph edges as a pandas DataFrame.

get_edge_series(attribute_name)

Return a single edge attribute as a pandas Series.

get_metadata(key=None)

Get metadata from the graph.

get_vertex_dataframe

Return graph vertices as a pandas DataFrame.

get_vertex_series(attribute_name)

Return a single vertex attribute as a pandas Series.

remove_attributes(attribute_type, attributes)

Remove specified attributes from vertices or edges.

remove_isolated_vertices(node_types='reactions')

Remove isolated vertices from the graph.

reverse_edges

Reverse all edges in the graph in-place.

set_graph_attrs(graph_attrs, mode='fresh', overwrite=False)

Set graph attributes from SBML_dfs or dictionary.

set_metadata(**kwargs)

Set metadata for the graph in-place.

set_weights(weighting_strategy='unweighted', weight_by=None, reaction_edge_multiplier=0.5)

Set edge weights using various strategies.

to_pandas_dfs

Convert graph to pandas DataFrames for vertices and edges.

to_pickle(path)

Save the NapistuGraph to a pickle file.

transform_edges(keep_raw_attributes=False, custom_transformations=None)

Transform edge attributes using predefined or custom transformations.

transform_vertices(keep_raw_attributes=False, custom_transformations=None)

Transform vertex attributes using predefined or custom transformations.

validate

Validate the graph structure and metadata.

Private/Hidden Methods (alphabetical, appear after public methods)
-----------------------------------------------------------------
_add_graph_weights_mixed(weight_by=None)

Add mixed weighting strategy to graph edges.

_add_entity_data(sbml_dfs, entity_type, target_entity, mode, overwrite, inplace)

Add entity data from SBML_dfs to the graph.

_apply_reaction_edge_multiplier(multiplier=0.5)

Apply multiplier to reaction edges.

_compare_and_merge_attrs(new_attrs, attr_type, mode='fresh', overwrite=False)

Compare and merge attributes with existing ones.

_create_source_weights(edges_df, source_wt_var='source_wt', source_vars_dict=SOURCE_VARS_DICT, source_wt_default=1)

Create source-based weights for edges.

_get_entity_attrs(entity_type)

Get entity-specific attributes from metadata.

_get_weight_variables(weight_by=None)

Get weight variables for edge weighting.

Examples

Create a NapistuGraph from scratch:

>>> ng = NapistuGraph(directed=True)
>>> ng.add_vertices(3)
>>> ng.add_edges([(0, 1), (1, 2)])

Convert from existing igraph:

>>> import igraph as ig
>>> g = ig.Graph.Erdos_Renyi(10, 0.3)
>>> ng = NapistuGraph.from_igraph(g, wiring_approach='regulatory')

Reverse edges and check state:

>>> ng.reverse_edges()
>>> print(ng.is_reversed)
True

Set and retrieve metadata:

>>> ng.set_metadata(experiment_id='exp_001', date='2024-01-01')
>>> print(ng.get_metadata('experiment_id'))
'exp_001'

Notes

NapistuGraph inherits from igraph.Graph, so all standard igraph methods (degree, shortest_paths, betweenness, etc.) are available. The additional functionality is designed specifically for molecular network analysis.

Edge reversal swaps ‘from’/’to’ attributes, negates stoichiometry values, and updates direction metadata according to predefined mapping rules.

classmethod from_igraph(graph: Graph, **metadata) NapistuGraph

Create a NapistuGraph from an existing igraph.Graph.

Parameters:
  • graph (ig.Graph) – The igraph to convert

  • **metadata (dict) – Additional metadata to store with the graph

Returns:

A new NapistuGraph instance

Return type:

NapistuGraph

classmethod from_pickle(path: str) NapistuGraph

Load a NapistuGraph from a pickle file.

Parameters:

path (str) – Path to the pickle file

Returns:

The loaded NapistuGraph object

Return type:

NapistuGraph

__init__(*args, **kwargs)

Initialize a NapistuGraph.

Accepts all the same arguments as igraph.Graph constructor.

_add_attributes_df(entity_data: DataFrame, target_entity: str, overwrite: bool = False) None

Add attributes to a graph in-place by merging entity data with graph data.

This private method performs the core operation of merging entity data with graph data and assigning the resulting attributes directly to the graph. It’s extracted from the _add_entity_data method for reusability.

Parameters:
  • entity_data (pd.DataFrame) – DataFrame containing the entity data to add, indexed by entity IDs. The merge will occur on any combination of columns present in the vertices/edges that match the index names of entity_data. For single index: uses the index name (e.g., “s_id” for species). For multi-index: uses the index names (e.g., [“from”, “to”] for edges).

  • target_entity (str) – Either “edges” or “vertices” - determines where to add the attributes

  • overwrite (bool, default=False) – Whether to allow overwriting existing attributes when conflicts arise

Return type:

None

Raises:

ValueError – If target_entity is not “edges” or “vertices”

_add_entity_data(entity_type: str, target_entity: str, sbml_dfs: SBML_dfs | None = None, side_loaded_attributes: dict[str, DataFrame] | None = None, mode: str = 'fresh', overwrite: bool = False, inplace: bool = True) NapistuGraph | None

Extract and add entity attributes to the graph edges or vertices.

This is a shared utility method used by add_edge_data and add_vertex_data.

Parameters:
  • entity_type (str) – Either “reactions” or “species”

  • target_entity (str) – Either “edges” or “vertices” - determines where to add the attributes

  • sbml_dfs (SBML_dfs) – The SBML_dfs object containing entity data. If None, only side-loaded attributes will be used.

  • side_loaded_attributes (dict[str, pd.DataFrame]) – A dictionary of side-loaded attributes. If None, only sbml_dfs will be used.

  • mode (str) – Either “fresh” (replace existing) or “extend” (add new attributes only)

  • overwrite (bool) – Whether to allow overwriting existing attributes when conflicts arise. Ignored if mode is “extend”.

  • inplace (bool, default=True) – Whether to modify the graph in place. If False, returns a copy with entity data.

Returns:

If inplace=True, returns None. If inplace=False, returns a new NapistuGraph with entity data added.

Return type:

Optional[NapistuGraph]

_add_graph_weights_mixed(weight_by: list[str] | None = None) None

Weight this NapistuGraph using a mixed approach combining source-specific weights and existing edge weights.

Modifies the graph in-place.

_apply_reaction_edge_multiplier(multiplier: float = 0.5) None

Apply multiplier to edges connected to reaction vertices.

This method modifies edge weights to account for path length differences between reaction-mediated connections (S → R → P) and direct connections (S → P).

Parameters:

multiplier (float) – Factor to multiply edge weights by. Values < 1.0 decrease weights, values > 1.0 increase weights.

Notes

  • Modifies both ‘weight’ and ‘upstream_weight’ attributes if they exist

  • Only affects edges that connect to/from reaction vertices

  • Preserves relative weight differences within modified edges

_cleanup_removed_attributes_metadata(attribute_type: str, removed_attributes: set[str]) None

Clean up metadata for removed attributes.

This method removes entries from the metadata that are no longer relevant after attributes have been removed from the graph.

Parameters:
  • attribute_type (str) – Type of attributes that were removed (NAPISTU_GRAPH.VERTICES or NAPISTU_GRAPH.EDGES)

  • removed_attributes (set[str]) – Set of attribute names that were removed

_compare_and_merge_attrs(new_attrs: dict, attr_type: str, mode: str = 'fresh', overwrite: bool = False) dict

Compare and merge new attributes with existing ones.

Parameters:
  • new_attrs (dict) – New attributes to add/merge

  • attr_type (str) – Type of attributes (“species_attrs” or “reaction_attrs”)

  • mode (str) – Either “fresh” (replace) or “extend” (add new keys)

  • overwrite (bool) – Whether to allow overwriting existing data (ignored if mode is “extend”)

Returns:

Merged attributes dictionary

Return type:

dict

_create_source_weights(edges_df: DataFrame, source_wt_var: str = 'source_wt', source_vars_dict: dict = {'string_wt': 10}, source_wt_default: float = 1) DataFrame

Create weights based on an edge’s source.

Parameters:
  • edges_df (pd.DataFrame) – The edges dataframe to add the source weights to.

  • source_wt_var (str, optional) – The name of the column to store the source weights. Default is “source_wt”.

  • source_vars_dict (dict, optional) – Dictionary with keys indicating edge attributes and values indicating the weight to assign to that attribute. Default is SOURCE_VARS_DICT.

  • source_wt_default (float, optional) – The default weight to assign to an edge if no other weight attribute is found. Default is 0.5.

Returns:

The edges dataframe with the source weights added.

Return type:

pd.DataFrame

_get_entity_attrs(entity_type: str) dict | None

Get entity attributes (species or reactions) from graph metadata.

Parameters:

entity_type (str) – Either “species” or “reactions”

Returns:

Valid entity_attrs dictionary, or None if none available

Return type:

dict or None

_get_weight_variables(weight_by: list[str] | None = None) dict

Get the variables to weight by, either from weight_by or reaction_attrs.

Parameters:

weight_by (list[str], optional) – A list of edge attributes to weight by. If None, uses reaction_attrs from metadata.

Returns:

Dictionary of reaction attributes to use for weighting.

Return type:

dict

Raises:

ValueError – If no weights are available or if specified weights do not exist as edge attributes.

_transform_entity_attributes(entity_type: str, target_entity: str, keep_raw_attributes: bool = False, custom_transformations: dict | None = None) None

Apply transformations to entity attributes (edges or vertices).

This is a shared utility method used by transform_edges and transform_vertices.

Parameters:
  • entity_type (str) – Either “reactions” or “species”

  • target_entity (str) – Either “edges” or “vertices” - determines where to apply transformations

  • keep_raw_attributes (bool) – If True, store untransformed attributes for future re-transformation

  • custom_transformations (dict, optional) – Dictionary mapping transformation names to functions

add_all_entity_data(sbml_dfs: SBML_dfs, entity_type: str, target_entity: str | None = None, table_names: list[str] | None = None, add_name_prefixes: bool = True, mode: str = 'fresh', overwrite: bool = False, inplace: bool = True) NapistuGraph | None

Add all data tables for a specific entity type to the graph.

This is a convenience method that automatically adds all available data tables for species or reactions without requiring manual configuration of each table and column.

Parameters:
  • sbml_dfs (SBML_dfs) – The SBML_dfs object containing entity data

  • entity_type (str) – Either “species” or “reactions”

  • target_entity (Optional[str], default=None) – Where to add the data: “vertices” or “edges”. If None, uses default mapping: - “species” -> “vertices” - “reactions” -> “edges” Explicit specification allows reactions data on vertices (bipartite graphs) or species data on edges (if such use case exists).

  • table_names (Optional[list[str]], default=None) – Specific table names to include. If None, includes all available tables.

  • add_name_prefixes (bool, default=True) – Whether to prefix attribute names with table name (e.g., “table_name_column_name”)

  • mode (str, default="fresh") – Either “fresh” (replace existing) or “extend” (add new attributes only)

  • overwrite (bool, default=False) – Whether to allow overwriting existing attributes when conflicts arise

  • inplace (bool, default=True) – Whether to modify the graph in place

Returns:

If inplace=True, returns None. Otherwise returns modified copy.

Return type:

Optional[NapistuGraph]

Raises:

ValueError – If entity_type is invalid or requested tables don’t exist

Examples

Add all species data to vertices (default): >>> graph.add_all_entity_data(sbml_dfs, “species”)

Add reactions data to reaction vertices (bipartite graph): >>> graph.add_all_entity_data(sbml_dfs, “reactions”, target_entity=”vertices”)

Add reactions data to edges (interaction graph): >>> graph.add_all_entity_data(sbml_dfs, “reactions”, target_entity=”edges”)

Add specific tables: >>> graph.add_all_entity_data(sbml_dfs, “reactions”, … table_names=[“experiments”, “literature”])

add_degree_attributes(inplace: bool = True) NapistuGraph | None

Calculate and add degree-based attributes (parents, children, degree) to the graph.

This method calculates the number of parents, children, and total degree for each node and stores these as edge attributes to support topology weighting. The attributes are calculated from the current graph’s edge data.

Parameters:

inplace (bool, default=True) – Whether to modify the graph in place. If False, returns a copy with degree attributes.

Returns:

If inplace=True, returns None. If inplace=False, returns a new NapistuGraph with degree attributes added to edges.

Return type:

Optional[NapistuGraph]

add_edge_data(sbml_dfs: SBML_dfs | None = None, side_loaded_attributes: dict[str, DataFrame] | None = None, mode: str = 'fresh', overwrite: bool = False, inplace: bool = True) NapistuGraph | None

Extract and add reaction attributes to the graph edges.

Parameters:
  • sbml_dfs (SBML_dfs) – The SBML_dfs object containing reaction data. If None, only side-loaded attributes will be used.

  • side_loaded_attributes (dict[str, pd.DataFrame], optional) – Dictionary mapping table names to DataFrames for side-loaded data

  • mode (str) – Either “fresh” (replace existing) or “extend” (add new attributes only)

  • overwrite (bool) – Whether to allow overwriting existing edge attributes when conflicts arise. Ignored if mode is “extend”.

  • inplace (bool, default=True) – Whether to modify the graph in place. If False, returns a copy with edge data.

Returns:

If inplace=True, returns None. If inplace=False, returns a new NapistuGraph with edge data added.

Return type:

Optional[NapistuGraph]

add_sbml_dfs_summaries(sbml_dfs: SBML_dfs, summary_types: list[str] = ['sources', 'ontologies'], priority_pathways: list[str] = ['BiGG', 'Dogma', 'IDEA', 'IntAct', 'OmniPath', 'Reactome', 'Reactome-FI', 'STRING', 'TRRUST', 'Recon3D', 'iMM1415', 'iMM904'], stratify_by_bqb: bool = True, characteristic_only: bool = False, dogmatic: bool = False, add_name_prefixes: bool = False, binarize: bool = False, mode: str = 'fresh', overwrite: bool = False, inplace: bool = True) NapistuGraph | None

Add vertex summaries from SBML_dfs to the graph vertices.

This method calls get_sbml_dfs_vertex_summaries and merges the results with the graph’s vertices by name.

Parameters:
  • sbml_dfs (SBML_dfs) – The SBML_dfs object to extract vertex summaries from

  • summary_types (list, optional) – Types of summaries to include. Defaults to all valid summary types.

  • priority_pathways (list, optional) – Priority pathways for source occurrence calculations. Defaults to DEFAULT_PRIORITIZED_PATHWAYS.

  • stratify_by_bqb (bool, optional) – Whether to stratify by BioQualifiers. Default is True.

  • characteristic_only (bool, optional) – Whether to include only characteristic identifiers. Default is False.

  • dogmatic (bool, optional) – Whether to use dogmatic mode. Default is False.

  • add_name_prefixes (bool, default False) – If True, add prefixes to column names: ‘source_’ for source data and ‘ontology_’ for ontology data

  • binarize (bool, optional) – Whether to convert the summary to binary values (0 vs 1+). Default is False.

  • mode (str) – Either “fresh” (replace existing) or “extend” (add new attributes only)

  • overwrite (bool) – Whether to allow overwriting existing vertex attributes when conflicts arise. Ignored if mode is “extend”.

  • inplace (bool, default=True) – Whether to modify the graph in place. If False, returns a copy with summary attributes.

Returns:

If inplace=True, returns None. If inplace=False, returns a new NapistuGraph with summary attributes added to vertices.

Return type:

Optional[NapistuGraph]

add_topology_weights(base_score: float = 2, protein_multiplier: int = 1, metabolite_multiplier: int = 3, drug_multiplier: int = 1, complex_multiplier: int = 3, unknown_multiplier: int = 10, scale_multiplier_by_meandegree: bool = True, inplace: bool = True) NapistuGraph | None

Create Topology Weights for a network based on its topology.

Edges downstream of nodes with many connections receive a higher weight suggesting that any one of them is less likely to be regulatory. This is a simple and clearly flawed heuristic which can be combined with more principled weighting schemes.

Parameters:
  • base_score (float, optional) – Offset which will be added to all weights. Default is 2.

  • protein_multiplier (int, optional) – Multiplier for non-metabolite species. Default is 1.

  • metabolite_multiplier (int, optional) – Multiplier for metabolites. Default is 3.

  • drug_multiplier (int, optional) – Multiplier for drugs. Default is 1.

  • complex_multiplier (int, optional) – Multiplier for complexes. Default is 3.

  • unknown_multiplier (int, optional) – Multiplier for species without any identifier. Default is 10.

  • scale_multiplier_by_meandegree (bool, optional) – If True, multipliers will be rescaled by the average number of connections a node has. Default is True.

  • inplace (bool, default=True) – Whether to modify the graph in place. If False, returns a copy with topology weights.

Returns:

If inplace=True, returns None. If inplace=False, returns a new NapistuGraph with topology weights added.

Return type:

Optional[NapistuGraph]

Raises:

ValueError – If required attributes are missing or if parameters are invalid.

add_vertex_data(sbml_dfs: SBML_dfs | None = None, side_loaded_attributes: dict[str, DataFrame] | None = None, mode: str = 'fresh', overwrite: bool = False, inplace: bool = True) NapistuGraph | None

Extract and add species attributes to the graph vertices.

Parameters:
  • sbml_dfs (SBML_dfs) – The SBML_dfs object containing species data. If None, only side-loaded attributes will be used.

  • side_loaded_attributes (dict[str, pd.DataFrame], optional) – Dictionary mapping table names to DataFrames for side-loaded data

  • mode (str) – Either “fresh” (replace existing) or “extend” (add new attributes only)

  • overwrite (bool) – Whether to allow overwriting existing vertex attributes when conflicts arise. Ignored if mode is “extend”.

  • inplace (bool, default=True) – Whether to modify the graph in place. If False, returns a copy with vertex data.

Returns:

If inplace=True, returns None. If inplace=False, returns a new NapistuGraph with vertex data added.

Return type:

Optional[NapistuGraph]

copy() NapistuGraph

Create a deep copy of the NapistuGraph.

Returns:

A deep copy of this graph including metadata

Return type:

NapistuGraph

deduplicate_edges(verbose: bool = False) None

Deduplicate edges with the same FROM -> TO pair, keeping only the first occurrence.

This identifies and removes duplicate edges between the same pair of vertices, keeping only the first edge encountered. Modifies the graph in-place.

Parameters:

verbose (bool, optional) – Whether to show example duplicate edges if duplicates are found. Default is False.

Return type:

None

filter_by_species_type(species_types: list[str], negate: bool = False, remove_unused_vertices: bool = True, inplace: bool = False, verbose: bool = False) NapistuGraph | None

Filter the graph to vertices whose species_type matches a list of valid types.

Returns the induced subgraph containing only vertices whose species_type vertex attribute is in valid_species_types, along with all edges between those retained vertices.

Parameters:
  • valid_species_types (list[str]) – Species type values to keep (e.g. ["protein", "metabolite"]). Vertices whose species_type is not in this list are removed. Vertices that lack a species_type attribute are also removed.

  • negate (bool, default False) – If False (default), keeps species whose species_type value is in the species_types arguments. If True, keeps species whose species_type value is not in the species_types arguments.

  • remove_unused_vertices (bool, default True) – Whether to remove vertices that are not used in any edges after filtering to the requested species types.

  • inplace (bool, default False) – If True, modify this graph in place and return None. If False (default), return a new NapistuGraph leaving this one unchanged. Note: inplace=True is destructive — vertices are permanently deleted.

  • verbose (bool, default False) – Whether to print verbose output

Returns:

A new NapistuGraph (inplace=False) or None (inplace=True).

Return type:

Optional[NapistuGraph]

Raises:

KeyError – If the graph has no species_type vertex attribute.

Examples

>>> ng.filter_by_species_type(["protein", "metabolite"], inplace=True)
get_edge_dataframe() DataFrame

Get edges as a Pandas DataFrame. Wrapper around igraph’s get_edge_dataframe method.

Returns:

A table with one row per edge.

Return type:

pandas.DataFrame

get_edge_endpoint_attributes(vertex_attribute_names: str | List[str]) DataFrame

Get source and target vertex attributes for all edges.

Creates a DataFrame with one row per edge containing the specified vertex attribute values for both the source and target nodes.

Parameters:

vertex_attribute_names (str or list of str) – Name(s) of vertex attribute(s) to extract for source and target nodes (e.g., ‘species_type’, [‘species_type’, ‘node_type’])

Returns:

DataFrame with row MultiIndex (from, to) and column MultiIndex (attribute_name, endpoint) where endpoint is ‘source’ or ‘target’

Return type:

pd.DataFrame

Raises:

KeyError – If any vertex attribute does not exist

Examples

>>> # Get single attribute
>>> species_df = graph.get_edge_endpoint_attributes('species_type')
>>> species_df.head()
                            species_type
                                source    target
from         to
R00000000    SC00015559          reaction metabolite
R00000214    SC00001716          reaction metabolite
>>> # Get multiple attributes at once
>>> edge_attrs = graph.get_edge_endpoint_attributes(['species_type', 'node_type'])
>>> edge_attrs.head()
                            species_type           node_type
                                source    target    source    target
from         to
R00000000    SC00015559          reaction metabolite  reaction  species
R00000214    SC00001716          reaction metabolite  reaction  species
>>> # Access specific columns
>>> edge_attrs[('species_type', 'source')]
>>> edge_attrs['species_type']  # Both source and target for species_type
>>> edge_attrs.xs('source', level='endpoint', axis=1)  # All source attributes
get_edge_series(attribute_name: str) Series

Get a single edge attribute as a pandas Series.

Parameters:

attribute_name (str) – Name of the edge attribute to extract

Returns:

Series with MultiIndex (from, to) as index and attribute values as data

Return type:

pd.Series

Raises:

KeyError – If the attribute does not exist on any edges

get_has_reactions() bool

Check if the graph contains reaction vertices.

Returns:

True if the graph contains reaction vertices, False otherwise.

Return type:

bool

get_metadata(key: str | None = None) Any

Get metadata from the graph.

Parameters:

key (str, optional) – Specific metadata key to retrieve. If None, returns all metadata.

Returns:

The requested metadata value, or all metadata if key is None

Return type:

Any

get_summary() Mapping[str, Any]

Get summary statistics for the graph.

Returns:

A dictionary of summary statistics. - n_vertices: Number of vertices - vertex_node_type_dict: Dictionary of node type counts - vertex_species_type_dict: Dictionary of species type counts - vertex_attributes: List of vertex attributes - n_edges: Number of edges - sbo_name_counts_dict: Dictionary of SBO name counts - edge_attributes: List of edge attributes

Return type:

Mapping[str, Any]

get_vertex_dataframe() DataFrame

Get vertices as a Pandas DataFrame. Wrapper around igraph’s get_vertex_dataframe method.

Returns:

A table with one row per vertex.

Return type:

pandas.DataFrame

get_vertex_series(attribute_name: str) Series

Get a single vertex attribute as a pandas Series.

Parameters:

attribute_name (str) – Name of the vertex attribute to extract

Returns:

Series with vertex names as index and attribute values as data

Return type:

pd.Series

Raises:

KeyError – If the attribute does not exist on any vertices

remove_attributes(attribute_type: str, attributes: list[str]) None

Remove specified attributes from vertices or edges.

This method removes the specified attributes from either vertices or edges and warns if any of the attributes to be removed are not associated with any vertices/edges in the graph.

Parameters:
  • attribute_type (str) – Type of attributes to remove. Must be either NAPISTU_GRAPH.VERTICES or NAPISTU_GRAPH.EDGES.

  • attributes (list[str]) – List of attribute names to remove from the specified attribute type.

Returns:

The graph is modified in-place.

Return type:

None

Raises:

ValueError – If attribute_type is not NAPISTU_GRAPH.VERTICES or NAPISTU_GRAPH.EDGES.

Examples

Remove vertex attributes: >>> graph.remove_attributes(NAPISTU_GRAPH.VERTICES, [“species_type”, “node_type”])

Remove edge attributes: >>> graph.remove_attributes(NAPISTU_GRAPH.EDGES, [“weight”, “stoichiometry”])

Notes

This method will warn about attributes that don’t exist in the graph but will continue to remove the attributes that do exist.

remove_isolated_vertices(node_types: str = 'reactions', verbose: bool = False)

Remove vertices that have no edges (degree 0) from the graph.

By default, only removes reaction singletons since these are not included in wiring by-construction for interaction edges. Species singletons may reflect that their reactions were specifically removed (e.g., water if cofactors are removed).

Parameters:
  • node_types (str, default="reactions") – Which type of isolated vertices to remove. Options: - “reactions”: Remove only isolated reaction vertices (default) - “species”: Remove only isolated species vertices - “all”: Remove all isolated vertices regardless of type

  • verbose (bool, default=False) – Whether to print verbose output

Returns:

The graph is modified in-place.

Return type:

None

reverse_edges() None

Reverse all edges in the graph.

This swaps edge directions and updates all associated attributes according to the edge reversal mapping utilities. Modifies the graph in-place.

Return type:

None

set_graph_attrs(graph_attrs: str | dict, mode: str = 'fresh', overwrite: bool = False, validate_transformations: bool = True, custom_transformations: dict | None = None) None

Set graph attributes from YAML file or dictionary.

Parameters:
  • graph_attrs (str or dict) – Either path to YAML file or dictionary with ‘species’ and/or ‘reactions’ keys

  • mode (str) – Either “fresh” (replace existing) or “extend” (add new keys)

  • overwrite (bool) – Whether to allow overwriting existing data when conflicts arise

  • validate_transformations (bool, default=True) – Whether to validate transformation names when setting up attributes

  • custom_transformations (dict, optional) – Dictionary of custom transformation functions for validation. The values should be functions.

set_metadata(**kwargs) None

Set metadata for the graph.

Modifies the graph’s metadata in-place.

Parameters:

**kwargs (dict) – Metadata key-value pairs to set

set_weights(weighting_strategy: str = 'unweighted', weight_by: list[str] | None = None, reaction_edge_multiplier: float = 0.5) None

Set Graph Weights for this NapistuGraph using a specified weighting strategy.

Modifies the graph in-place. Now includes functionality to downweight edges connected to reaction vertices to account for increased path lengths through reaction intermediates (e.g., S → R → P vs direct S → P).

Parameters:
  • weight_by (list[str], optional) – A list of edge attributes to weight by. How these are used depends on the weighting strategy.

  • weighting_strategy (str, optional) –

    A network weighting strategy. Options: ‘unweighted’: all weights (and upstream_weight for directed graphs) are set to 1. ‘topology’: weight edges by the degree of the source nodes favoring nodes

    emerging from nodes with few connections.

    ’mixed’: transform edges with a quantitative score based on reaction_attrs;

    and set edges without quantitative score as a source-specific weight.

  • reaction_edge_multiplier (float, optional) – Factor to multiply weights of edges connected to reaction vertices. Default 0.5 reduces reaction edge weights by 50% to normalize path lengths. Set to 1.0 to disable this feature.

Raises:

ValueError – If weighting_strategy is not valid.

Notes

The reaction_edge_multiplier addresses the issue where SBML-derived networks have paths like S → R → P (length 2) compared to direct protein interactions S → P (length 1). A multiplier of 0.5 makes these path costs equivalent.

show_summary() None

Show summary statistics for the graph.

to_pandas_dfs() tuple[DataFrame, DataFrame]

Convert this NapistuGraph to Pandas DataFrames for vertices and edges.

Returns:

  • vertices (pandas.DataFrame) – A table with one row per vertex.

  • edges (pandas.DataFrame) – A table with one row per edge.

to_pickle(path: str) None

Save the NapistuGraph to a pickle file.

Parameters:

path (str) – Path where to save the pickle file

transform_edges(keep_raw_attributes: bool = False, custom_transformations: dict | None = None) None

Apply transformations to edge attributes based on stored reaction_attrs.

Parameters:
  • keep_raw_attributes (bool) – If True, store untransformed attributes for future re-transformation

  • custom_transformations (dict, optional) – Dictionary mapping transformation names to functions

transform_vertices(keep_raw_attributes: bool = False, custom_transformations: dict | None = None) None

Apply transformations to vertex attributes based on stored species_attrs.

Parameters:
  • keep_raw_attributes (bool) – If True, store untransformed attributes for future re-transformation

  • custom_transformations (dict, optional) – Dictionary mapping transformation names to functions

validate() None

Validate the NapistuGraph structure and attributes.

This method performs various validation checks to ensure the graph is properly structured and has required attributes.

Raises:

ValueError – If validation fails with specific details about the issue

property is_reversed: bool

Check if the graph has been reversed.

property weight_by: list[str] | None

Get the weight_by attributes used.

property weighting_strategy: str | None

Get the weighting strategy used.

property wiring_approach: str | None

Get the graph type (bipartite, regulatory, etc.).

napistu.network.ng_core._apply_edge_reversal_mapping(edges_df: DataFrame) DataFrame

Apply systematic attribute mapping for edge reversal.

This function swaps paired attributes according to EDGE_REVERSAL_ATTRIBUTE_MAPPING. For example, ‘from’ becomes ‘to’, ‘weight’ becomes ‘upstream_weight’, etc.

Parameters:

edges_df (pd.DataFrame) – Current edge attributes

Returns:

Edge dataframe with swapped attributes

Return type:

pd.DataFrame

Warning

Logs warnings when expected attribute pairs are missing

napistu.network.ng_core._handle_special_reversal_cases(edges_df: DataFrame, ignore_direction: bool = False) DataFrame

Handle special cases that need more than simple attribute swapping.

This includes: - Flipping stoichiometry signs (* -1) for upstream and downstream stoichiometries - Mapping direction enums (forward <-> reverse)

Parameters:
  • edges_df (pd.DataFrame) – Edge dataframe after basic attribute swapping (upstream/downstream already swapped)

  • ignore_direction (bool, default=False) – If True, skip the direction attribute check and mapping. Useful when the direction attribute doesn’t exist yet (e.g., during initial network creation).

Returns:

Edge dataframe with special cases handled

Return type:

pd.DataFrame

Warning

Logs warnings when expected attributes are missing (unless ignore_direction=True)