Compatibility Layer API
The compatibility layer provides lossless conversion between py3plex and external graph libraries.
Main Conversion API
- py3plex.compat.convert(graph: Any, target: str, *, strict: bool = True, sidecar: str | None = 'auto', **kwargs) Any
Convert a graph to a target format with lossless preservation.
This is the main entry point for graph conversion. It routes to specific converters based on the target format.
- Parameters:
graph – Source graph (py3plex graph, NetworkX, scipy sparse, etc.)
target – Target format name: - “networkx”: NetworkX graph - “scipy_sparse”: SciPy sparse matrix - “igraph”: igraph graph (requires python-igraph) - “pyg”: PyTorch Geometric Data (requires torch-geometric) - “dgl”: DGL graph (requires dgl)
strict – If True, raise exception if target cannot represent all data. If False, use sidecar bundle to preserve data.
sidecar – Path for sidecar bundle (used in non-strict mode). “auto” generates a path based on target. None disables sidecar.
**kwargs – Additional arguments passed to specific converters
- Returns:
Converted graph in target format
- Raises:
ConversionNotSupportedError – If target is not recognized or available
CompatibilityError – In strict mode, if target cannot represent the graph
Examples
>>> # Convert py3plex to NetworkX >>> nx_graph = convert(py3_graph, "networkx")
>>> # Convert to scipy sparse with sidecar for attributes >>> matrix = convert(py3_graph, "scipy_sparse", strict=False, sidecar="my_graph")
>>> # Convert from NetworkX to py3plex (via "py3plex" target) >>> py3_graph = convert(nx_graph, "py3plex")
- py3plex.compat.to_ir(graph: Any) GraphIR
Convert a py3plex graph to Intermediate Representation.
- Parameters:
graph – A py3plex graph object (MultiLayerGraph or multi_layer_network)
- Returns:
Intermediate representation of the graph
- Return type:
- Raises:
TypeError – If graph type is not supported
- py3plex.compat.from_ir(ir: GraphIR, target_type: str = 'multilayer_graph') Any
Convert Intermediate Representation to a py3plex graph.
- Parameters:
ir – GraphIR intermediate representation
target_type – Type of graph to create (“multilayer_graph” or “multi_layer_network”)
- Returns:
A py3plex graph object
- Raises:
ValueError – If target_type is not supported
Intermediate Representation
- class py3plex.compat.GraphIR(nodes: NodeTable, edges: EdgeTable, meta: GraphMeta)
Intermediate Representation for graph data.
This is the canonical format used by all converters to ensure lossless roundtrip conversion.
- nodes
Node table with IDs, ordering, and attributes
- edges
Edge table with IDs, ordering, and attributes
- meta
Graph-level metadata
- to_dict() Dict[str, Any]
Convert to dictionary representation.
- class py3plex.compat.NodeTable(node_id: List[Hashable], node_order: List[int], attrs: DataFrame | None = None, layer: List[str] | None = None)
Tabular representation of nodes with deterministic ordering.
- node_id
List of node identifiers (hashable)
- Type:
List[Hashable]
- node_order
List of integer indices for deterministic ordering
- Type:
List[int]
- attrs
DataFrame of node attributes (or dict mapping node_id to attrs)
- Type:
pandas.core.frame.DataFrame | None
- layer
Optional layer assignment for multilayer networks
- Type:
List[str] | None
- attrs: DataFrame | None = None
- layer: List[str] | None = None
- node_id: List[Hashable]
- node_order: List[int]
- to_dict() Dict[str, Any]
Convert to dictionary representation.
- class py3plex.compat.EdgeTable(edge_id: List[Hashable], src: List[Hashable], dst: List[Hashable], edge_order: List[int], attrs: DataFrame | None = None, src_layer: List[str] | None = None, dst_layer: List[str] | None = None, key: List[int] | None = None)
Tabular representation of edges with deterministic ordering.
- edge_id
List of edge identifiers for multigraph support
- Type:
List[Hashable]
- src
List of source node IDs
- Type:
List[Hashable]
- dst
List of destination node IDs
- Type:
List[Hashable]
- edge_order
List of integer indices for deterministic ordering
- Type:
List[int]
- attrs
DataFrame of edge attributes (or dict mapping edge_id to attrs)
- Type:
pandas.core.frame.DataFrame | None
- src_layer
Optional source layer for multilayer networks
- Type:
List[str] | None
- dst_layer
Optional destination layer for multilayer networks
- Type:
List[str] | None
- key
Optional list of edge keys for multigraph support (default: 0 for each edge)
- Type:
List[int] | None
- attrs: DataFrame | None = None
- dst: List[Hashable]
- dst_layer: List[str] | None = None
- edge_id: List[Hashable]
- edge_order: List[int]
- key: List[int] | None = None
- src: List[Hashable]
- src_layer: List[str] | None = None
- to_dict() Dict[str, Any]
Convert to dictionary representation.
- class py3plex.compat.GraphMeta(directed: bool = False, multi: bool = False, name: str | None = None, created_by: str = 'py3plex', py3plex_version: str | None = None, schema_version: str = '1.0', global_attrs: ~typing.Dict[str, ~typing.Any] = <factory>, layers: ~typing.List[str] | None = None)
Graph-level metadata.
- directed
Whether the graph is directed
- Type:
bool
- multi
Whether the graph is a multigraph (parallel edges allowed)
- Type:
bool
- name
Optional graph name
- Type:
str | None
- created_by
Tool/library that created the graph
- Type:
str
- py3plex_version
Version of py3plex used
- Type:
str | None
- schema_version
IR schema version
- Type:
str
- global_attrs
Additional graph-level attributes
- Type:
Dict[str, Any]
- layers
List of layer identifiers for multilayer networks
- Type:
List[str] | None
- created_by: str = 'py3plex'
- directed: bool = False
- global_attrs: Dict[str, Any]
- layers: List[str] | None = None
- multi: bool = False
- name: str | None = None
- py3plex_version: str | None = None
- schema_version: str = '1.0'
- to_dict() Dict[str, Any]
Convert to dictionary representation.
Schema Validation
- class py3plex.compat.GraphSchema(directed: bool = False, multi: bool = False, node_id_type: str = 'mixed', edge_id_required: bool = False, node_attr_types: ~typing.Dict[str, str] = <factory>, edge_attr_types: ~typing.Dict[str, str] = <factory>, unsafe_types: ~typing.List[str] = <factory>, has_layers: bool = False, layer_count: int | None = None)
Schema specification for graph data.
This describes the structure and types of a graph for compatibility checking.
- directed
Whether the graph is directed
- Type:
bool
- multi
Whether the graph supports parallel edges
- Type:
bool
- node_id_type
Type of node identifiers (e.g., “int”, “str”, “mixed”)
- Type:
str
- edge_id_required
Whether edge IDs must be present
- Type:
bool
- node_attr_types
Mapping of node attribute names to types
- Type:
Dict[str, str]
- edge_attr_types
Mapping of edge attribute names to types
- Type:
Dict[str, str]
- unsafe_types
List of attribute types that may not serialize cleanly
- Type:
List[str]
- has_layers
Whether the graph has multilayer structure
- Type:
bool
- layer_count
Number of layers (None if not multilayer)
- Type:
int | None
- directed: bool = False
- edge_attr_types: Dict[str, str]
- edge_id_required: bool = False
- classmethod from_dict(data: Dict[str, Any]) GraphSchema
Create schema from dictionary.
- has_layers: bool = False
- layer_count: int | None = None
- multi: bool = False
- node_attr_types: Dict[str, str]
- node_id_type: str = 'mixed'
- to_dict() Dict[str, Any]
Convert schema to dictionary.
- unsafe_types: List[str]
- py3plex.compat.infer_schema(ir: GraphIR) GraphSchema
Infer schema from GraphIR.
Analyzes the IR to determine types and characteristics for compatibility checking.
- Parameters:
ir – GraphIR to analyze
- Returns:
GraphSchema describing the IR
- py3plex.compat.validate_against_schema(ir: GraphIR, schema: GraphSchema) ValidationReport
Validate GraphIR against a schema.
Checks that the IR conforms to the expected schema specification.
- Parameters:
ir – GraphIR to validate
schema – Expected schema
- Returns:
ValidationReport with validation results
Equality Checking
- py3plex.compat.ir_equals(a: GraphIR, b: GraphIR, *, ignore_order: bool = False, tolerance: float = 1e-09) bool
Check if two GraphIR objects are equal.
- Parameters:
a – First GraphIR
b – Second GraphIR
ignore_order – If True, ignore node_order and edge_order differences
tolerance – Numerical tolerance for float comparisons
- Returns:
True if GraphIRs are equal, False otherwise
Examples
>>> ir1 = to_ir(graph) >>> ir2 = to_ir(graph) >>> assert ir_equals(ir1, ir2)
- py3plex.compat.ir_diff(a: GraphIR, b: GraphIR) List[str]
Generate a list of differences between two GraphIR objects.
- Parameters:
a – First GraphIR
b – Second GraphIR
- Returns:
List of difference descriptions (empty if equal)
Examples
>>> diffs = ir_diff(ir1, ir2) >>> if diffs: ... for diff in diffs: ... print(f"Difference: {diff}")
Sidecar Bundles
- py3plex.compat.sidecar.export_sidecar(ir: GraphIR, path: str, *, format: Literal['json+parquet', 'json+csv'] = 'json+parquet') None
Export GraphIR to sidecar bundle.
- Parameters:
ir – GraphIR to export
path – Path for sidecar bundle (directory will be created)
format – Storage format: - “json+parquet”: JSON metadata + Parquet tables (requires pyarrow) - “json+csv”: JSON metadata + CSV tables (fallback)
- Raises:
ImportError – If pyarrow is required but not available
Exceptions
- exception py3plex.compat.exceptions.CompatibilityError(message: str, reason: str | None = None, suggestions: list[str] | None = None)
Bases:
ExceptionRaised when a conversion cannot preserve all data in the target format.
This exception is raised in strict mode when the target format cannot represent some aspect of the source graph (e.g., multigraph edges in a simple graph format, or complex attributes in a matrix format).
- message
Human-readable error message
- reason
Specific reason for incompatibility
- suggestions
List of suggested remediation actions
- exception py3plex.compat.exceptions.SchemaError(message: str, field: str | None = None, expected: Any | None = None, actual: Any | None = None)
Bases:
ExceptionRaised when schema validation or inference fails.
This exception is raised when: - Schema validation detects type mismatches or invalid data - Schema inference encounters ambiguous or unsupported types - Required schema constraints are violated
- message
Human-readable error message
- field
The field or attribute that caused the error
- expected
Expected type or value
- actual
Actual type or value found
- exception py3plex.compat.exceptions.ConversionNotSupportedError
Bases:
ExceptionRaised when a requested conversion is not supported.
This exception is raised when: - The target format is not recognized or implemented - Required optional dependencies are not installed - The conversion is fundamentally incompatible (e.g., temporal to static)
Converters
NetworkX
- py3plex.compat.converters.networkx_converter.to_networkx_from_ir(ir: GraphIR, *, strict: bool = True, preserve_layers: bool = True, **kwargs) Graph
Convert GraphIR to NetworkX graph.
- Parameters:
ir – GraphIR to convert
strict – If True, raise exception on incompatibilities (currently always succeeds)
preserve_layers – If True, preserve layer information in node/edge attributes
**kwargs – Additional keyword arguments (unused)
- Returns:
NetworkX graph (Graph, DiGraph, MultiGraph, or MultiDiGraph)
- Raises:
CompatibilityError – In strict mode, if conversion would lose data (rare)
SciPy Sparse
- py3plex.compat.converters.scipy_converter.to_scipy_sparse_from_ir(ir: GraphIR, *, weight: str = 'weight', strict: bool = True, sidecar: str | None = None, format: str = 'csr', **kwargs) spmatrix
Convert GraphIR to SciPy sparse matrix.
- Parameters:
ir – GraphIR to convert
weight – Edge attribute to use as matrix values (default: “weight”)
strict – If True, raise exception if multigraph or attributes cannot be represented
sidecar – Path for sidecar bundle to preserve non-matrix data (required in non-strict mode)
format – Sparse matrix format (“csr”, “csc”, “coo”, etc.)
**kwargs – Additional arguments
- Returns:
SciPy sparse matrix
- Raises:
CompatibilityError – In strict mode, if graph cannot be represented as matrix
- py3plex.compat.converters.scipy_converter.from_scipy_sparse_to_ir(matrix: spmatrix, *, node_ids: List[Any] | None = None, directed: bool = True, weight_attr: str = 'weight', sidecar: str | None = None, **kwargs) GraphIR
Convert SciPy sparse matrix to GraphIR.
- Parameters:
matrix – Sparse matrix to convert
node_ids – Optional list of node identifiers (default: 0, 1, 2, …)
directed – Whether to treat matrix as directed
weight_attr – Name for edge weight attribute
sidecar – Path to sidecar bundle to load additional data
**kwargs – Additional arguments
- Returns:
GraphIR representation
igraph
- py3plex.compat.converters.igraph_converter.to_igraph_from_ir(ir: GraphIR, *, strict: bool = True, **kwargs) Any
Convert GraphIR to igraph graph.
- Parameters:
ir – GraphIR to convert
strict – If True, raise on incompatibilities
**kwargs – Additional arguments
- Returns:
igraph Graph object
- Raises:
ConversionNotSupportedError – If igraph is not installed
- py3plex.compat.converters.igraph_converter.from_igraph_to_ir(g: Any) GraphIR
Convert igraph graph to GraphIR.
- Parameters:
g – igraph Graph object
- Returns:
GraphIR representation
- Raises:
ConversionNotSupportedError – If igraph is not installed