Interoperability
This section covers in-memory adapters and file-format IO used to exchange AnnNet graphs with external tools and formats.
In-Memory Backends
NetworkX (optional)
The NetworkX adapter requires the networkx extra. Public entry points:
to_nx(graph, ...)from_nx(G, ...)from_nx_only(G, ...)to_backend(graph, ...)save_manifest(manifest, path)load_manifest(path)
See annnet.adapters.networkx_adapter in source for full details.
igraph (optional)
annnet.adapters.igraph_adapter
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
IGraphAdapter
Legacy adapter class for backward compatibility.
Methods:
| Name | Description |
|---|---|
export |
Export AnnNet to igraph.AnnNet without manifest (lossy). |
Functions
export(graph, **kwargs)
Export AnnNet to igraph.AnnNet without manifest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
|
required |
**kwargs
|
See to_backend() for supported parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_endpoint_coeff_map(edge_attrs, private_key, endpoint_set)
Return {vertex: float_coeff} for the given endpoint_set. Reads from edge_attrs[private_key], which may be serialized in multiple shapes. Missing endpoints default to 1.0.
_is_directed_eid(graph, eid)
Best-effort directedness probe; default True.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_collect_slices_and_weights(graph)
Returns: slices_section: {slice_id: [edge_id, ...]} slice_weights: {slice_id: {edge_id: weight}} Backends supported: Polars-like, .to_dicts()-like, dict.
_serialize_value(v)
_attrs_to_dict(attrs_dict)
_rows(t)
Backend-agnostic: convert a table-ish object to list[dict].
_safe_df_to_rows(df)
Never crash if df is None or backend is missing.
_export_legacy(graph, *, directed=True, skip_hyperedges=True, public_only=False)
Export AnnNet to igraph.AnnNet without manifest.
igraph requires integer vertex indices; external vertex IDs are preserved in vertex attribute 'name'. Edge IDs stored in edge attribute 'eid'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
Source graph instance. |
required |
directed
|
bool
|
If True, export as directed igraph.AnnNet; else undirected. Undirected edges in directed export are emitted bidirectionally. |
True
|
skip_hyperedges
|
bool
|
If True, drop hyperedges. If False: - directed hyperedges expand head×tail (cartesian product) - undirected hyperedges expand to clique |
True
|
public_only
|
bool
|
If True, strip private attrs starting with "__". |
False
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
_coeff_from_obj(obj)
to_igraph(graph, directed=True, hyperedge_mode='skip', slice=None, slices=None, public_only=False, reify_prefix='he::')
Export AnnNet → (igraph.AnnNet, manifest).
hyperedge_mode: {"skip","expand","reify"} - "skip": drop HE edges from igG (manifest keeps them) - "expand": cartesian product (directed) / clique (undirected) - "reify": add a node per HE and membership edges V↔HE carrying roles/coeffs
save_manifest(manifest, path)
Write manifest to JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
dict
|
Manifest dictionary from to_igraph(). |
required |
path
|
str
|
Output file path (typically .json extension). |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
OSError
|
If file cannot be written. |
load_manifest(path)
Load manifest from JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to manifest JSON file created by save_manifest(). |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Manifest dictionary suitable for from_igraph(). |
Raises:
| Type | Description |
|---|---|
OSError
|
If file cannot be read. |
JSONDecodeError
|
If file contains invalid JSON. |
_ig_collect_reified(igG, he_node_flag='is_hyperedge', he_id_attr='eid', role_attr='role', coeff_attr='coeff', membership_attr='membership_of')
Scan igG for reified hyperedges.
Returns: - hyperdefs: list of (eid, directed:bool, head_map:dict, tail_map:dict, he_node_attrs:dict, he_vertex_index) - membership_edge_idx: set of edge indices that are membership edges (to skip for binary import)
from_igraph(igG, manifest, *, hyperedge='none', he_node_flag='is_hyperedge', he_id_attr='eid', reify_prefix='he::')
Reconstruct a AnnNet from igraph.AnnNet + manifest.
hyperedge: "none" (default) | "reified" When "reified", also detect hyperedge nodes in igG and rebuild true hyperedges that are NOT present in the manifest.
to_backend(graph, **kwargs)
Export AnnNet to igraph without manifest (legacy compatibility).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
Source AnnNet instance to export. |
required |
**kwargs
|
Forwarded to _export_legacy(). Supported: - directed : bool, default True Export as directed igraph.AnnNet (True) or undirected (False). - skip_hyperedges : bool, default True If True, drop hyperedges. If False, expand them (cartesian product for directed, clique for undirected). - public_only : bool, default False Strip attributes starting with "__" if True. |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
igraph.AnnNet with integer vertex indices. External vertex IDs are stored in vertex attribute 'name'. Edge IDs stored in edge attribute 'eid'. Hyperedges are either dropped or expanded into multiple binary edges. No manifest is returned, so round-tripping will lose hyperedge structure, slices, and precise edge IDs. |
Notes
This is a lossy export. Use to_igraph() with manifest for full fidelity. igraph requires integer vertex indices internally; the 'name' attribute preserves your original string IDs.
from_ig_only(igG, *, hyperedge='none', he_node_flag='is_hyperedge', he_id_attr='eid', role_attr='role', coeff_attr='coeff', membership_attr='membership_of')
Best-effort import from a plain igraph.AnnNet (no manifest). Preserves all vertex/edge attributes. hyperedge: "none" | "reified" When "reified", rebuild true hyperedges and skip membership edges from binary import.
Internal helpers
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
IGraphAdapter
Legacy adapter class for backward compatibility.
Methods:
| Name | Description |
|---|---|
export |
Export AnnNet to igraph.AnnNet without manifest (lossy). |
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_endpoint_coeff_map(edge_attrs, private_key, endpoint_set)
Return {vertex: float_coeff} for the given endpoint_set. Reads from edge_attrs[private_key], which may be serialized in multiple shapes. Missing endpoints default to 1.0.
_is_directed_eid(graph, eid)
Best-effort directedness probe; default True.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_collect_slices_and_weights(graph)
Returns: slices_section: {slice_id: [edge_id, ...]} slice_weights: {slice_id: {edge_id: weight}} Backends supported: Polars-like, .to_dicts()-like, dict.
_serialize_value(v)
_attrs_to_dict(attrs_dict)
_rows(t)
Backend-agnostic: convert a table-ish object to list[dict].
_safe_df_to_rows(df)
Never crash if df is None or backend is missing.
_export_legacy(graph, *, directed=True, skip_hyperedges=True, public_only=False)
Export AnnNet to igraph.AnnNet without manifest.
igraph requires integer vertex indices; external vertex IDs are preserved in vertex attribute 'name'. Edge IDs stored in edge attribute 'eid'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
Source graph instance. |
required |
directed
|
bool
|
If True, export as directed igraph.AnnNet; else undirected. Undirected edges in directed export are emitted bidirectionally. |
True
|
skip_hyperedges
|
bool
|
If True, drop hyperedges. If False: - directed hyperedges expand head×tail (cartesian product) - undirected hyperedges expand to clique |
True
|
public_only
|
bool
|
If True, strip private attrs starting with "__". |
False
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
_coeff_from_obj(obj)
to_igraph(graph, directed=True, hyperedge_mode='skip', slice=None, slices=None, public_only=False, reify_prefix='he::')
Export AnnNet → (igraph.AnnNet, manifest).
hyperedge_mode: {"skip","expand","reify"} - "skip": drop HE edges from igG (manifest keeps them) - "expand": cartesian product (directed) / clique (undirected) - "reify": add a node per HE and membership edges V↔HE carrying roles/coeffs
save_manifest(manifest, path)
Write manifest to JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
dict
|
Manifest dictionary from to_igraph(). |
required |
path
|
str
|
Output file path (typically .json extension). |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
OSError
|
If file cannot be written. |
load_manifest(path)
Load manifest from JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to manifest JSON file created by save_manifest(). |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Manifest dictionary suitable for from_igraph(). |
Raises:
| Type | Description |
|---|---|
OSError
|
If file cannot be read. |
JSONDecodeError
|
If file contains invalid JSON. |
_ig_collect_reified(igG, he_node_flag='is_hyperedge', he_id_attr='eid', role_attr='role', coeff_attr='coeff', membership_attr='membership_of')
Scan igG for reified hyperedges.
Returns: - hyperdefs: list of (eid, directed:bool, head_map:dict, tail_map:dict, he_node_attrs:dict, he_vertex_index) - membership_edge_idx: set of edge indices that are membership edges (to skip for binary import)
from_igraph(igG, manifest, *, hyperedge='none', he_node_flag='is_hyperedge', he_id_attr='eid', reify_prefix='he::')
Reconstruct a AnnNet from igraph.AnnNet + manifest.
hyperedge: "none" (default) | "reified" When "reified", also detect hyperedge nodes in igG and rebuild true hyperedges that are NOT present in the manifest.
to_backend(graph, **kwargs)
Export AnnNet to igraph without manifest (legacy compatibility).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
Source AnnNet instance to export. |
required |
**kwargs
|
Forwarded to _export_legacy(). Supported: - directed : bool, default True Export as directed igraph.AnnNet (True) or undirected (False). - skip_hyperedges : bool, default True If True, drop hyperedges. If False, expand them (cartesian product for directed, clique for undirected). - public_only : bool, default False Strip attributes starting with "__" if True. |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
igraph.AnnNet with integer vertex indices. External vertex IDs are stored in vertex attribute 'name'. Edge IDs stored in edge attribute 'eid'. Hyperedges are either dropped or expanded into multiple binary edges. No manifest is returned, so round-tripping will lose hyperedge structure, slices, and precise edge IDs. |
Notes
This is a lossy export. Use to_igraph() with manifest for full fidelity. igraph requires integer vertex indices internally; the 'name' attribute preserves your original string IDs.
from_ig_only(igG, *, hyperedge='none', he_node_flag='is_hyperedge', he_id_attr='eid', role_attr='role', coeff_attr='coeff', membership_attr='membership_of')
Best-effort import from a plain igraph.AnnNet (no manifest). Preserves all vertex/edge attributes. hyperedge: "none" | "reified" When "reified", rebuild true hyperedges and skip membership edges from binary import.
graph-tool (optional)
annnet.adapters.graphtool_adapter
AnnNet-tool adapter for AnnNet AnnNet.
Provides: to_graphtool(G) -> (gt.Graph, manifest_dict) from_graphtool(gtG, manifest=None) -> AnnNet
graph-tool only gets what it can natively represent:
- vertices (type 'vertex')
- simple binary edges with a global directedness + a 'weight' edge property
Everything else (hyperedges, per-edge directedness, multilayer, slices,
all attribute tables, etc.) is preserved in manifest.
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_slices(data)
Inverse of _serialize_slices.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_slices(slices)
_slices is {slice_id: {"vertices": set, "edges": set, "attributes": dict}} Convert sets to lists for JSON.
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
to_graphtool(G, *, vertex_id_property='id', edge_id_property='id', weight_property='weight')
Convert an AnnNet AnnNet -> (graph_tool.AnnNet, manifest).
graph-tool graph: - vertices: only entities with entity_types[u] == "vertex" - edges: only binary edges whose endpoints are such vertices - vertex property vp[vertex_id_property] = AnnNet vertex id - edge property ep[edge_id_property] = AnnNet edge id - edge property ep[weight_property] = edge weight (float)
manifest: - preserves everything graph-tool cannot: hyperedges, slices, multilayer, and ALL attribute tables.
from_graphtool(gtG, manifest=None, *, vertex_id_property='id', edge_id_property='id', weight_property='weight')
Convert graph_tool.AnnNet (+ optional manifest) back into AnnNet AnnNet.
- Vertices: from vertex property
vertex_id_propertyif present, else numeric index. - Edges: from edges in gtG; edge_id from edge property
edge_id_propertyif present, else auto; weight from edge propertyweight_propertyif present, else 1.0.
If manifest is provided, rehydrates:
- all attribute tables (vertex/edge/slice/edge_slice/layer),
- _slices internal structure,
- hyperedges,
- edge_directed and edge_direction_policy,
- multilayer (aspects, elem_layers, VM, aspect attrs, layer-tuple attrs,
edge_kind, edge_layers, node-layer attrs),
- graph_attributes.
Internal helpers
AnnNet-tool adapter for AnnNet AnnNet.
Provides: to_graphtool(G) -> (gt.Graph, manifest_dict) from_graphtool(gtG, manifest=None) -> AnnNet
graph-tool only gets what it can natively represent:
- vertices (type 'vertex')
- simple binary edges with a global directedness + a 'weight' edge property
Everything else (hyperedges, per-edge directedness, multilayer, slices,
all attribute tables, etc.) is preserved in manifest.
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_slices(data)
Inverse of _serialize_slices.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_slices(slices)
_slices is {slice_id: {"vertices": set, "edges": set, "attributes": dict}} Convert sets to lists for JSON.
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
to_graphtool(G, *, vertex_id_property='id', edge_id_property='id', weight_property='weight')
Convert an AnnNet AnnNet -> (graph_tool.AnnNet, manifest).
graph-tool graph: - vertices: only entities with entity_types[u] == "vertex" - edges: only binary edges whose endpoints are such vertices - vertex property vp[vertex_id_property] = AnnNet vertex id - edge property ep[edge_id_property] = AnnNet edge id - edge property ep[weight_property] = edge weight (float)
manifest: - preserves everything graph-tool cannot: hyperedges, slices, multilayer, and ALL attribute tables.
from_graphtool(gtG, manifest=None, *, vertex_id_property='id', edge_id_property='id', weight_property='weight')
Convert graph_tool.AnnNet (+ optional manifest) back into AnnNet AnnNet.
- Vertices: from vertex property
vertex_id_propertyif present, else numeric index. - Edges: from edges in gtG; edge_id from edge property
edge_id_propertyif present, else auto; weight from edge propertyweight_propertyif present, else 1.0.
If manifest is provided, rehydrates:
- all attribute tables (vertex/edge/slice/edge_slice/layer),
- _slices internal structure,
- hyperedges,
- edge_directed and edge_direction_policy,
- multilayer (aspects, elem_layers, VM, aspect attrs, layer-tuple attrs,
edge_kind, edge_layers, node-layer attrs),
- graph_attributes.
PyTorch Geometric (optional)
The PyG adapter requires torch + torch_geometric. Public entry point:
to_pyg(graph, ...)
See annnet.adapters.pyg_adapter in source for full details.
Adapter Manager
annnet.adapters.manager
Classes
BackendProxy
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
load_adapter(name, *args, **kwargs)
get_adapter(name)
Return a new adapter instance for the optional backend.
get_proxy(backend_name, graph)
Return a lazy proxy so users can write G.nx.<algo>() etc.
_backend_import_name(name)
ensure_materialized(backend_name, graph)
Convert (or re-convert) graph into the requested backend object and cache the result on the graph’s private state object. Returns:
Internal helpers
Classes
BackendProxy
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
load_adapter(name, *args, **kwargs)
get_adapter(name)
Return a new adapter instance for the optional backend.
get_proxy(backend_name, graph)
Return a lazy proxy so users can write G.nx.<algo>() etc.
_backend_import_name(name)
ensure_materialized(backend_name, graph)
Convert (or re-convert) graph into the requested backend object and cache the result on the graph’s private state object. Returns:
File Formats
GraphML / GEXF (via NetworkX, optional)
The GraphML/GEXF helpers require NetworkX. Public entry points:
to_graphml(graph, path, ...)from_graphml(path, ...)to_gexf(graph, path, ...)from_gexf(path, ...)
See annnet.io.GraphML_io in source for full details.
SIF
annnet.io.SIF_io
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_split_sif_line(line, delimiter)
_safe_vertex_attr_table(graph)
_get_all_edge_attrs(graph, edge_id)
_get_edge_weight(graph, edge_id, default=1.0)
_build_edge_attr_map(graph)
to_sif(graph, path=None, *, relation_attr='relation', default_relation='interacts_with', write_nodes=True, nodes_path=None, lossless=False, manifest_path=None)
Export graph to SIF format.
Standard mode (lossless=False): - Writes only binary edges to SIF file - Hyperedges, weights, attrs, IDs are lost - Returns None
Lossless mode (lossless=True): - Writes binary edges to SIF file - Returns (None, manifest) where manifest contains all lost info - Manifest can be saved separately and used with from_sif()
Args: path: Output SIF file path (if None, only manifest is returned in lossless mode) relation_attr: Edge attribute key for relation type default_relation: Default relation if attr missing write_nodes: Whether to write .nodes sidecar with vertex attrs nodes_path: Custom path for nodes sidecar (default: path + ".nodes") lossless: If True, return manifest with all non-SIF data manifest_path: If provided, write manifest to this path (only when lossless=True)
Returns: None (standard mode) or (None, manifest_dict) (lossless mode)
from_sif(path, *, manifest=None, directed=True, relation_attr='relation', default_relation='interacts_with', read_nodes_sidecar=True, nodes_path=None, encoding='utf-8', delimiter=None, comment_prefixes=('#', '!'))
Import graph from SIF (Simple Interaction Format).
Standard mode (manifest=None):
- Reads binary edges from SIF file (source, relation, target)
- Auto-generates edge IDs (edge_0, edge_1, ...)
- All edges inherit the directed parameter
- Vertex attributes loaded from optional .nodes sidecar
- Hyperedges, per-edge directedness, and complex metadata are lost
Lossless mode (manifest provided): - Reads binary edges from SIF file - Restores original edge IDs, weights, and attributes from manifest - Reconstructs hyperedges from manifest - Restores per-edge directedness from manifest - Restores slice memberships and slice-specific weights from manifest - Full round-trip fidelity when paired with to_sif(lossless=True)
SIF Format:
- Three columns: source
Sidecar .nodes file format (optional):
- One vertex per line: vertex_id
Args: path: Input SIF file path manifest: Manifest dict or path to manifest JSON (for lossless reconstruction) directed: Default directedness for edges (overridden by manifest if provided) relation_attr: Edge attribute key for storing relation type default_relation: Default relation if not specified in file read_nodes_sidecar: Whether to read .nodes sidecar file with vertex attributes nodes_path: Custom path for nodes sidecar (default: path + ".nodes") encoding: File encoding (default: utf-8) delimiter: Custom delimiter (default: auto-detect TAB or whitespace) comment_prefixes: Line prefixes to skip (default: # and !)
Returns: AnnNet: Reconstructed graph object
Notes: - SIF format only supports binary edges natively - For full graph reconstruction (hyperedges, slices, metadata), use manifest - Manifest files are created by to_sif(lossless=True) - Edge IDs are auto-generated in standard mode, preserved in lossless mode - Vertex attributes require .nodes sidecar file or manifest
Internal helpers
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_split_sif_line(line, delimiter)
_safe_vertex_attr_table(graph)
_get_all_edge_attrs(graph, edge_id)
_get_edge_weight(graph, edge_id, default=1.0)
_build_edge_attr_map(graph)
to_sif(graph, path=None, *, relation_attr='relation', default_relation='interacts_with', write_nodes=True, nodes_path=None, lossless=False, manifest_path=None)
Export graph to SIF format.
Standard mode (lossless=False): - Writes only binary edges to SIF file - Hyperedges, weights, attrs, IDs are lost - Returns None
Lossless mode (lossless=True): - Writes binary edges to SIF file - Returns (None, manifest) where manifest contains all lost info - Manifest can be saved separately and used with from_sif()
Args: path: Output SIF file path (if None, only manifest is returned in lossless mode) relation_attr: Edge attribute key for relation type default_relation: Default relation if attr missing write_nodes: Whether to write .nodes sidecar with vertex attrs nodes_path: Custom path for nodes sidecar (default: path + ".nodes") lossless: If True, return manifest with all non-SIF data manifest_path: If provided, write manifest to this path (only when lossless=True)
Returns: None (standard mode) or (None, manifest_dict) (lossless mode)
from_sif(path, *, manifest=None, directed=True, relation_attr='relation', default_relation='interacts_with', read_nodes_sidecar=True, nodes_path=None, encoding='utf-8', delimiter=None, comment_prefixes=('#', '!'))
Import graph from SIF (Simple Interaction Format).
Standard mode (manifest=None):
- Reads binary edges from SIF file (source, relation, target)
- Auto-generates edge IDs (edge_0, edge_1, ...)
- All edges inherit the directed parameter
- Vertex attributes loaded from optional .nodes sidecar
- Hyperedges, per-edge directedness, and complex metadata are lost
Lossless mode (manifest provided): - Reads binary edges from SIF file - Restores original edge IDs, weights, and attributes from manifest - Reconstructs hyperedges from manifest - Restores per-edge directedness from manifest - Restores slice memberships and slice-specific weights from manifest - Full round-trip fidelity when paired with to_sif(lossless=True)
SIF Format:
- Three columns: source
Sidecar .nodes file format (optional):
- One vertex per line: vertex_id
Args: path: Input SIF file path manifest: Manifest dict or path to manifest JSON (for lossless reconstruction) directed: Default directedness for edges (overridden by manifest if provided) relation_attr: Edge attribute key for storing relation type default_relation: Default relation if not specified in file read_nodes_sidecar: Whether to read .nodes sidecar file with vertex attributes nodes_path: Custom path for nodes sidecar (default: path + ".nodes") encoding: File encoding (default: utf-8) delimiter: Custom delimiter (default: auto-detect TAB or whitespace) comment_prefixes: Line prefixes to skip (default: # and !)
Returns: AnnNet: Reconstructed graph object
Notes: - SIF format only supports binary edges natively - For full graph reconstruction (hyperedges, slices, metadata), use manifest - Manifest files are created by to_sif(lossless=True) - Edge IDs are auto-generated in standard mode, preserved in lossless mode - Vertex attributes require .nodes sidecar file or manifest
SBML
annnet.io.SBML_io
Attributes
BOUNDARY_SOURCE = '__BOUNDARY_SOURCE__'
module-attribute
BOUNDARY_SINK = '__BOUNDARY_SINK__'
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_call(obj, method, default=None)
Call obj.method() if it exists, else return default.
_isset(obj, setter_name)
Return True if obj has an isSet* method that returns True.
_ensure_boundary_vertices(G, slice)
_read_sbml_model(path)
_register_compartments(G, model, default_slice)
Create one AnnNet slice per SBML compartment, carrying compartment metadata. No-ops gracefully if the graph or model does not support the required API.
_register_species(G, model, default_slice)
Add all species as vertices into their compartment slice. Returns a mapping sid -> compartment_id for later use by reactions.
_graph_from_sbml_model(model, graph=None, *, slice='default', preserve_stoichiometry=True)
Build an AnnNet from an SBML model using only libSBML.
Vertices : SBML species ids assigned to their compartment slice. Boundary placeholders go into the default slice. Slices : One AnnNet slice per SBML compartment (with metadata). Hyperedges: reactions — tail = reactants + modifiers, head = products. Stoichiometry: reactants : -stoich (consumed) products : +stoich (produced) modifiers : -1.0 (regulatory input, not consumed) Edge attrs: reversible, name, sbo_term, kinetic_law, local_params, modifier_roles, compartment, meta_id, is_boundary, …
from_sbml(path, graph=None, *, slice='default', preserve_stoichiometry=True)
Read an SBML file into an AnnNet hypergraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the .xml / .sbml file. |
required |
graph
|
AnnNet | None
|
Optional existing AnnNet to merge into. |
None
|
slice
|
str
|
AnnNet slice name for default placement. Compartment-specific species will additionally appear in their compartment slice. |
'default'
|
preserve_stoichiometry
|
bool
|
Write signed stoichiometric coefficients into the incidence matrix via set_hyperedge_coeffs (reactants negative, products positive, modifiers -1). Default True. |
True
|
Internal helpers
Attributes
BOUNDARY_SOURCE = '__BOUNDARY_SOURCE__'
module-attribute
BOUNDARY_SINK = '__BOUNDARY_SINK__'
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_call(obj, method, default=None)
Call obj.method() if it exists, else return default.
_isset(obj, setter_name)
Return True if obj has an isSet* method that returns True.
_ensure_boundary_vertices(G, slice)
_read_sbml_model(path)
_register_compartments(G, model, default_slice)
Create one AnnNet slice per SBML compartment, carrying compartment metadata. No-ops gracefully if the graph or model does not support the required API.
_register_species(G, model, default_slice)
Add all species as vertices into their compartment slice. Returns a mapping sid -> compartment_id for later use by reactions.
_graph_from_sbml_model(model, graph=None, *, slice='default', preserve_stoichiometry=True)
Build an AnnNet from an SBML model using only libSBML.
Vertices : SBML species ids assigned to their compartment slice. Boundary placeholders go into the default slice. Slices : One AnnNet slice per SBML compartment (with metadata). Hyperedges: reactions — tail = reactants + modifiers, head = products. Stoichiometry: reactants : -stoich (consumed) products : +stoich (produced) modifiers : -1.0 (regulatory input, not consumed) Edge attrs: reversible, name, sbo_term, kinetic_law, local_params, modifier_roles, compartment, meta_id, is_boundary, …
from_sbml(path, graph=None, *, slice='default', preserve_stoichiometry=True)
Read an SBML file into an AnnNet hypergraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the .xml / .sbml file. |
required |
graph
|
AnnNet | None
|
Optional existing AnnNet to merge into. |
None
|
slice
|
str
|
AnnNet slice name for default placement. Compartment-specific species will additionally appear in their compartment slice. |
'default'
|
preserve_stoichiometry
|
bool
|
Write signed stoichiometric coefficients into the incidence matrix via set_hyperedge_coeffs (reactants negative, products positive, modifiers -1). Default True. |
True
|
SBML (COBRA)
annnet.io.sbml_cobra_io
SBML (Systems Biology Markup Language) → AnnNet adapter
Targets the provided AnnNet API.
Two entry points: - from_sbml(path, graph=None, slice="default", preserve_stoichiometry=True) - from_cobra_model(model, graph=None, slice="default", preserve_stoichiometry=True)
If AnnNet.set_hyperedge_coeffs(edge_id, coeffs: dict[str, float]) is not available,
stoichiometric coefficients are stored under an edge attribute stoich (lossy but usable).
Attributes
BOUNDARY_SOURCE = '__BOUNDARY_SOURCE__'
module-attribute
BOUNDARY_SINK = '__BOUNDARY_SINK__'
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_monkeypatch_set_hyperedge_coeffs(G)
Add set_hyperedge_coeffs(edge_id, coeffs) to AnnNet instance if missing.
Writes per-vertex coefficients into the incidence column (DOK [Dictionary Of Keys]).
Returns True if patch was applied, False if already available.
_ensure_vertices(G, vertices, slice)
_ensure_boundary_vertices(G, slice)
_graph_from_stoich(S, metabolite_ids, reaction_ids, graph=None, *, slice='default', preserve_stoichiometry=True)
from_cobra_model(model, graph=None, *, slice='default', preserve_stoichiometry=True)
Convert a COBRApy model to AnnNet. Requires cobra.util.array.create_stoichiometric_matrix. Edge attributes added: name, default_lb, default_ub, gpr (Gene-Protein-Reaction rule [GPR]).
from_sbml(path, graph=None, *, slice='default', preserve_stoichiometry=True, quiet=True)
Read SBML using COBRApy if available; falls back to python-libsbml (if you extend this file).
Internal helpers
SBML (Systems Biology Markup Language) → AnnNet adapter
Targets the provided AnnNet API.
Two entry points: - from_sbml(path, graph=None, slice="default", preserve_stoichiometry=True) - from_cobra_model(model, graph=None, slice="default", preserve_stoichiometry=True)
If AnnNet.set_hyperedge_coeffs(edge_id, coeffs: dict[str, float]) is not available,
stoichiometric coefficients are stored under an edge attribute stoich (lossy but usable).
Attributes
BOUNDARY_SOURCE = '__BOUNDARY_SOURCE__'
module-attribute
BOUNDARY_SINK = '__BOUNDARY_SINK__'
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_monkeypatch_set_hyperedge_coeffs(G)
Add set_hyperedge_coeffs(edge_id, coeffs) to AnnNet instance if missing.
Writes per-vertex coefficients into the incidence column (DOK [Dictionary Of Keys]).
Returns True if patch was applied, False if already available.
_ensure_vertices(G, vertices, slice)
_ensure_boundary_vertices(G, slice)
_graph_from_stoich(S, metabolite_ids, reaction_ids, graph=None, *, slice='default', preserve_stoichiometry=True)
from_cobra_model(model, graph=None, *, slice='default', preserve_stoichiometry=True)
Convert a COBRApy model to AnnNet. Requires cobra.util.array.create_stoichiometric_matrix. Edge attributes added: name, default_lb, default_ub, gpr (Gene-Protein-Reaction rule [GPR]).
from_sbml(path, graph=None, *, slice='default', preserve_stoichiometry=True, quiet=True)
Read SBML using COBRApy if available; falls back to python-libsbml (if you extend this file).
CX2
annnet.io.cx2_io
CX2 Adapter for AnnNet AnnNet.
Provides: to_cx2(G) -> List[Dict[str, Any]] (CX2 JSON object) from_cx2(cx2_data) -> AnnNet
This adapter maps AnnNet Graphs to the Cytoscape Exchange (CX2) format. It creates a lossless representation by serializing complex features (hyperedges, slices, multilayer) into a 'manifest' stored within the CX2 'networkAttributes'.
Attributes
CX_STYLE_KEY = '__cx_style__'
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_slices(data)
Inverse of _serialize_slices.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_safe_df_to_rows(df)
Return list[dict] rows from polars/pandas/narwhals; return [] on None/empty/unknown.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_slices(slices)
_slices is {slice_id: {"vertices": set, "edges": set, "attributes": dict}} Convert sets to lists for JSON.
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_cx2_collect_reified(aspects)
Detect reified hyperedges from CX2 nodes + edges.
Returns: hyperdefs: list of (eid, directed, head_map, tail_map, attrs, he_node_id) membership_edges: set of edge-ids in CX2 that belong to hyperedge membership structure.
_rows_to_df(rows)
_map_pl_to_cx2_type(dtype)
Map Polars DataType to CX2 attribute data type string.
_jsonify(obj)
to_cx2(G, *, export_name='annnet export', layer=None, include_inter=False, include_coupling=False, hyperedges='skip')
Convert an AnnNet graph to CX2 compliant JSON format.
The output is a list of aspect dictionaries (CX2 format). Complex AnnNet features (hyperedges, slices, multilayer structure) are serialized into a JSON string stored in networkAttributes under 'AnnNet_Manifest'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
The graph to export. |
required |
export_name
|
str
|
Name of the exported network (stored in networkAttributes). |
"annnet export"
|
layer
|
tuple of str
|
Elementary layer tuple specifying which layer to export. If provided, only the subgraph for that layer is exported. Useful for multilayer graphs where flattening creates unreadable visualizations in Cytoscape (e.g., coupling edges become self-loops). If None, exports the entire graph. Example: layer=("social", "2020") for a 2-aspect multilayer network. |
None
|
hyperedges
|
('skip', 'expand', 'reify')
|
How to handle hyperedges in the export: - "skip": Omit hyperedges entirely - "expand": Convert to cartesian product of pairwise edges - "reify": Create explicit hyperedge nodes with membership edges |
"skip"
|
Returns:
| Type | Description |
|---|---|
list of dict
|
CX2-compliant JSON structure (list of aspect dictionaries). |
Notes
- Cytoscape does not natively support multilayer networks. When exporting multilayer graphs without specifying a layer, coupling edges may appear as self-loops and the visualization becomes cluttered.
- Use the
layerparameter to export individual elementary layers for clean, interpretable Cytoscape visualizations. - The full multilayer structure is preserved in the manifest regardless
of the
layerparameter, enabling lossless round-trip via from_cx2().
from_cx2(cx2_data, *, hyperedges='manifest')
Fully robust CX2 - AnnNet importer. Supports: - manifest reconstruction (full fidelity) - reified hyperedges - expanded hyperedges - Cytoscape-edited files - sparse attribute tables - arbitrary attribute modifications
show(G, *, export_name='annnet export', layer=None, include_inter=False, include_coupling=False, hyperedges='skip', port=None, auto_open=True)
Visualize graph in web browser using Cytoscape.js.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
The graph to visualize. |
required |
export_name
|
str
|
Name of the network display. |
"annnet export"
|
layer
|
tuple of str
|
Elementary layer tuple specifying which layer to visualize. If None, shows the entire graph (may include coupling edges as self-loops). Example: layer=("social", "2020") for a 2-aspect multilayer network. |
None
|
include_inter
|
bool
|
When layer is specified, whether to include interlayer edges (edges between nodes in different layers but same aspect). Only relevant if layer is not None. |
False
|
include_coupling
|
bool
|
When layer is specified, whether to include coupling edges (edges connecting the same node across layers). Only relevant if layer is not None. Warning: Including coupling creates self-loops in the visualization. |
False
|
hyperedges
|
('skip', 'expand', 'reify')
|
How to handle hyperedges: - "skip": Omit hyperedges entirely - "expand": Convert to cartesian product of pairwise edges - "reify": Create explicit hyperedge nodes with membership edges |
"skip"
|
port
|
int
|
Port for local web server. If None, finds available port automatically. |
None
|
auto_open
|
bool
|
If True, automatically open browser. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Local URL to the visualization. |
Notes
For multilayer graphs: - Without layer parameter: shows entire flattened graph with coupling edges appearing as self-loops (messy but shows full structure) - With layer parameter: shows clean single-layer view without coupling edges (recommended for visualization)
Press Ctrl+C in terminal to stop the web server.
Examples:
_cx2_to_cytoscapejs(cx2_data)
Convert CX2 format to Cytoscape.js format.
Internal helpers
CX2 Adapter for AnnNet AnnNet.
Provides: to_cx2(G) -> List[Dict[str, Any]] (CX2 JSON object) from_cx2(cx2_data) -> AnnNet
This adapter maps AnnNet Graphs to the Cytoscape Exchange (CX2) format. It creates a lossless representation by serializing complex features (hyperedges, slices, multilayer) into a 'manifest' stored within the CX2 'networkAttributes'.
Attributes
CX_STYLE_KEY = '__cx_style__'
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_slices(data)
Inverse of _serialize_slices.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_safe_df_to_rows(df)
Return list[dict] rows from polars/pandas/narwhals; return [] on None/empty/unknown.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_slices(slices)
_slices is {slice_id: {"vertices": set, "edges": set, "attributes": dict}} Convert sets to lists for JSON.
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_cx2_collect_reified(aspects)
Detect reified hyperedges from CX2 nodes + edges.
Returns: hyperdefs: list of (eid, directed, head_map, tail_map, attrs, he_node_id) membership_edges: set of edge-ids in CX2 that belong to hyperedge membership structure.
_rows_to_df(rows)
_map_pl_to_cx2_type(dtype)
Map Polars DataType to CX2 attribute data type string.
_jsonify(obj)
to_cx2(G, *, export_name='annnet export', layer=None, include_inter=False, include_coupling=False, hyperedges='skip')
Convert an AnnNet graph to CX2 compliant JSON format.
The output is a list of aspect dictionaries (CX2 format). Complex AnnNet features (hyperedges, slices, multilayer structure) are serialized into a JSON string stored in networkAttributes under 'AnnNet_Manifest'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
The graph to export. |
required |
export_name
|
str
|
Name of the exported network (stored in networkAttributes). |
"annnet export"
|
layer
|
tuple of str
|
Elementary layer tuple specifying which layer to export. If provided, only the subgraph for that layer is exported. Useful for multilayer graphs where flattening creates unreadable visualizations in Cytoscape (e.g., coupling edges become self-loops). If None, exports the entire graph. Example: layer=("social", "2020") for a 2-aspect multilayer network. |
None
|
hyperedges
|
('skip', 'expand', 'reify')
|
How to handle hyperedges in the export: - "skip": Omit hyperedges entirely - "expand": Convert to cartesian product of pairwise edges - "reify": Create explicit hyperedge nodes with membership edges |
"skip"
|
Returns:
| Type | Description |
|---|---|
list of dict
|
CX2-compliant JSON structure (list of aspect dictionaries). |
Notes
- Cytoscape does not natively support multilayer networks. When exporting multilayer graphs without specifying a layer, coupling edges may appear as self-loops and the visualization becomes cluttered.
- Use the
layerparameter to export individual elementary layers for clean, interpretable Cytoscape visualizations. - The full multilayer structure is preserved in the manifest regardless
of the
layerparameter, enabling lossless round-trip via from_cx2().
from_cx2(cx2_data, *, hyperedges='manifest')
Fully robust CX2 - AnnNet importer. Supports: - manifest reconstruction (full fidelity) - reified hyperedges - expanded hyperedges - Cytoscape-edited files - sparse attribute tables - arbitrary attribute modifications
show(G, *, export_name='annnet export', layer=None, include_inter=False, include_coupling=False, hyperedges='skip', port=None, auto_open=True)
Visualize graph in web browser using Cytoscape.js.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
The graph to visualize. |
required |
export_name
|
str
|
Name of the network display. |
"annnet export"
|
layer
|
tuple of str
|
Elementary layer tuple specifying which layer to visualize. If None, shows the entire graph (may include coupling edges as self-loops). Example: layer=("social", "2020") for a 2-aspect multilayer network. |
None
|
include_inter
|
bool
|
When layer is specified, whether to include interlayer edges (edges between nodes in different layers but same aspect). Only relevant if layer is not None. |
False
|
include_coupling
|
bool
|
When layer is specified, whether to include coupling edges (edges connecting the same node across layers). Only relevant if layer is not None. Warning: Including coupling creates self-loops in the visualization. |
False
|
hyperedges
|
('skip', 'expand', 'reify')
|
How to handle hyperedges: - "skip": Omit hyperedges entirely - "expand": Convert to cartesian product of pairwise edges - "reify": Create explicit hyperedge nodes with membership edges |
"skip"
|
port
|
int
|
Port for local web server. If None, finds available port automatically. |
None
|
auto_open
|
bool
|
If True, automatically open browser. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Local URL to the visualization. |
Notes
For multilayer graphs: - Without layer parameter: shows entire flattened graph with coupling edges appearing as self-loops (messy but shows full structure) - With layer parameter: shows clean single-layer view without coupling edges (recommended for visualization)
Press Ctrl+C in terminal to stop the web server.
Examples:
_cx2_to_cytoscapejs(cx2_data)
Convert CX2 format to Cytoscape.js format.
JSON / NDJSON
annnet.io.json_io
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_is_directed_eid(graph, eid)
_coerce_coeff_mapping(val)
Normalize various serialized forms into {vertex: {__value: float}|float} Accepts: - dict({v: x} or {v: {"__value": x}}) - list of pairs [(v,x), ...] - list of dicts [{"vertex": v, "__value": x} | {v: x}, ...] - JSON string of any of the above
_endpoint_coeff_map(edge_attrs, private_key, endpoint_set)
Return {vertex: float_coeff} for the given endpoint_set. Reads from edge_attrs[private_key] which may be serialized in multiple shapes. Missing endpoints default to 1.0.
to_json(graph, path, *, public_only=False, indent=0)
Node-link JSON with x-extensions (slices, edge_slices, hyperedges). Lossless vs your core (IDs, attrs, parallel, hyperedges, slices).
from_json(path)
Load AnnNet from node-link JSON + x-extensions (lossless wrt schema above).
write_ndjson(graph, dir_path)
Write nodes.ndjson, edges.ndjson, hyperedges.ndjson, slices.ndjson, edge_slices.ndjson. Each line is one JSON object. Lossless wrt to_json schema.
Internal helpers
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_deserialize_edge_layers(data)
Inverse of _serialize_edge_layers.
Returns eid -> aa or (aa, bb) (tuples).
_deserialize_layer_tuple_attrs(data)
Inverse of _serialize_layer_tuple_attrs.
_deserialize_node_layer_attrs(data)
Inverse of _serialize_node_layer_attrs.
_deserialize_VM(data)
Inverse of _serialize_VM.
_df_to_rows(df)
Convert a Polars DataFrame to list-of-dicts in a stable way.
_rows_to_df(rows)
Build a Polars DataFrame from list-of-dicts. Empty -> empty DF.
_serialize_edge_layers(edge_layers)
Convert edge_layers[eid] (aa or (aa, bb)) into JSON-safe form.
- intra: aa -> {"kind": "single", "layers": [list(aa)]}
- inter/coupling: (aa, bb) -> {"kind": "pair", "layers": [list(aa), list(bb)]}
_serialize_layer_tuple_attrs(layer_attrs)
_layer_attrs: {aa_tuple -> {attr_name: value}} -> JSON-safe: [{"layer": list(aa), "attrs": {...}}, ...]
_serialize_node_layer_attrs(nl_attrs)
(u, aa) -> {attrs} -> [{"node": u, "layer": list(aa), "attrs": {...}}, ...]
_serialize_VM(VM)
Serialize V_M = {(u, aa)} to JSON-safe list of dicts.
_is_directed_eid(graph, eid)
_coerce_coeff_mapping(val)
Normalize various serialized forms into {vertex: {__value: float}|float} Accepts: - dict({v: x} or {v: {"__value": x}}) - list of pairs [(v,x), ...] - list of dicts [{"vertex": v, "__value": x} | {v: x}, ...] - JSON string of any of the above
_endpoint_coeff_map(edge_attrs, private_key, endpoint_set)
Return {vertex: float_coeff} for the given endpoint_set. Reads from edge_attrs[private_key] which may be serialized in multiple shapes. Missing endpoints default to 1.0.
to_json(graph, path, *, public_only=False, indent=0)
Node-link JSON with x-extensions (slices, edge_slices, hyperedges). Lossless vs your core (IDs, attrs, parallel, hyperedges, slices).
from_json(path)
Load AnnNet from node-link JSON + x-extensions (lossless wrt schema above).
write_ndjson(graph, dir_path)
Write nodes.ndjson, edges.ndjson, hyperedges.ndjson, slices.ndjson, edge_slices.ndjson. Each line is one JSON object. Lossless wrt to_json schema.
CSV
annnet.io.csv_io
This module purposefully avoids importing stdlib csv and uses Polars for IO.
It ingests a CSV into AnnNet by auto-detecting common schemas: - Edge list (including DOK/COO triples and variations) - Hyperedge table (members column or head/tail sets) - Incidence matrix (rows=entities, cols=edges, ±w orientation) - Adjacency matrix (square matrix, weighted/unweighted) - LIL-style neighbor lists (single column of neighbors)
If auto-detection fails or you want control, pass schema=... explicitly.
Dependencies: polars, numpy, scipy (only if you use sparse helpers), AnnNet
Design notes:
- We treat unknown columns as attributes ("pure" non-structural) and write them via
the corresponding set_*_attrs APIs when applicable.
- slices: if a slice column exists it can contain a single slice or multiple
(separated by |, ;, or ,). Per-slice weight overrides support columns of the
form weight:<slice_name>.
- Directedness: we honor an explicit directed column when present (truthy), else
infer for incidence (presence of negative values) and adjacency (symmetry check).
- We try not to guess too hard. If the heuristics get it wrong, supply
schema="edge_list" / "hyperedge" / "incidence" / "adjacency" / "lil".
Public entry points: - load_csv_to_graph(path, graph=None, schema="auto", options) -> AnnNet - from_dataframe(df, graph=None, schema="auto", options) -> AnnNet
Both will create and return an AnnNet (or mutate the provided one).
Attributes
_STR_TRUE = {'1', 'true', 't', 'yes', 'y', 'on'}
module-attribute
_STR_FALSE = {'0', 'false', 'f', 'no', 'n', 'off'}
module-attribute
_slice_SEP = re.compile('[|;,]')
module-attribute
_SET_SEP = re.compile('[|;,]\\s*')
module-attribute
SRC_COLS = ['source', 'src', 'from', 'u']
module-attribute
DST_COLS = ['target', 'dst', 'to', 'v']
module-attribute
WGT_COLS = ['weight', 'w']
module-attribute
DIR_COLS = ['directed', 'is_directed', 'dir', 'orientation']
module-attribute
slice_COLS = ['slice', 'slices']
module-attribute
EDGE_ID_COLS = ['edge', 'edge_id', 'id']
module-attribute
vertex_ID_COLS = ['vertex', 'vertex_id', 'id', 'name', 'label']
module-attribute
NEIGH_COLS = ['neighbors', 'nbrs', 'adj', 'adjacency', 'neighbors_out', 'neighbors_in']
module-attribute
MEMBERS_COLS = ['members', 'verts', 'participants']
module-attribute
HEAD_COLS = ['head', 'heads']
module-attribute
TAIL_COLS = ['tail', 'tails']
module-attribute
ROW_COLS = ['row', 'i', 'r']
module-attribute
COL_COLS = ['col', 'column', 'j', 'c']
module-attribute
VAL_COLS = ['val', 'value', 'w', 'weight']
module-attribute
RESERVED = set(SRC_COLS + DST_COLS + WGT_COLS + DIR_COLS + slice_COLS + EDGE_ID_COLS + vertex_ID_COLS + NEIGH_COLS + MEMBERS_COLS + HEAD_COLS + TAIL_COLS + ROW_COLS + COL_COLS + VAL_COLS)
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
_norm(s)
_truthy(x)
_split_slices(cell)
_split_set(cell)
_pick_first(df, candidates)
_is_numeric_series(s)
_attr_columns(df, exclude)
_detect_schema(df)
load_csv_to_graph(path, *, graph=None, schema='auto', default_slice=None, default_directed=None, default_weight=1.0, infer_schema_length=10000, encoding=None, null_values=None, low_memory=True, **kwargs)
Load a CSV and construct/augment an AnnNet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the CSV file. |
required |
graph
|
AnnNet or None
|
If provided, mutate this graph; otherwise create a new AnnNet using
|
None
|
schema
|
('auto', 'edge_list', 'hyperedge', 'incidence', 'adjacency', 'lil')
|
Parsing mode. 'auto' tries to infer the schema from columns and types. |
'auto','edge_list','hyperedge','incidence','adjacency','lil'
|
default_slice
|
str or None
|
slice to register vertices/edges when none is specified in the data. |
None
|
default_directed
|
bool or None
|
Default directedness for binary edges when not implied by data. |
None
|
default_weight
|
float
|
Default weight when not specified. |
1.0
|
infer_schema_length
|
int
|
Row count Polars uses to infer column types. |
10000
|
encoding
|
str or None
|
File encoding override. |
None
|
null_values
|
list[str] or None
|
Additional strings to interpret as nulls. |
None
|
low_memory
|
bool
|
Pass to Polars read_csv for balanced memory usage. |
True
|
**kwargs
|
Any
|
Passed to AnnNet constructor if |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
The populated graph instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no AnnNet can be constructed or imported. |
ValueError
|
If schema is unknown or parsing fails. |
from_dataframe(df, *, graph=None, schema='auto', default_slice=None, default_directed=None, default_weight=1.0, **kwargs)
Build/augment an AnnNet from a Polars DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input table parsed from CSV. |
required |
graph
|
AnnNet or None
|
If provided, mutate this graph; otherwise create a new AnnNet using
|
None
|
schema
|
('auto', 'edge_list', 'hyperedge', 'incidence', 'adjacency', 'lil')
|
Parsing mode. 'auto' tries to infer the schema. |
'auto','edge_list','hyperedge','incidence','adjacency','lil'
|
default_slice
|
str or None
|
Fallback slice if no slice is specified in the data. |
None
|
default_directed
|
bool or None
|
Default directedness for binary edges when not implied by data. |
None
|
default_weight
|
float
|
Weight to use when no explicit weight is present. |
1.0
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
The populated graph instance. |
export_edge_list_csv(G, path, slice=None)
Export the binary edge subgraph to a CSV [Comma-Separated Values] file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
AnnNet instance to export. Must support |
required |
path
|
str or Path
|
Output path for the CSV file. |
required |
slice
|
str
|
Restrict the export to a specific slice. If None, all slices are exported. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
- Only binary edges are exported. Hyperedges (edges connecting more than two entities) are ignored.
- Output columns include: 'source', 'target', 'weight', 'directed', and 'slice'.
- If a weight column does not exist, a default weight of 1.0 is written.
- If a directedness column is absent, it will be written as
None. - This format is compatible with
load_csv_to_graph(schema="edge_list").
export_hyperedge_csv(G, path, slice=None, directed=None)
Export hyperedges from the graph to a CSV [Comma-Separated Values] file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
AnnNet instance to export. Must support |
required |
path
|
str or Path
|
Output path for the CSV file. |
required |
slice
|
str
|
Restrict the export to a specific slice. If None, all slices are exported. |
None
|
directed
|
bool
|
Force treatment of hyperedges as directed or undirected. If None, the function attempts to infer directedness from the graph. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
- If the graph exposes a 'members' column, the output will contain one row per undirected hyperedge.
- If 'head' and 'tail' columns are present, the output will contain one row per
directed hyperedge. If
directed=Falseis passed, 'head' and 'tail' are merged into a 'members' column. - A 'weight' column is included if available; otherwise, all weights default to 1.0.
- A 'slice' column is included if present or if
sliceis specified. - This format is compatible with
load_csv_to_graph(schema="hyperedge"). - If the graph does not expose hyperedge columns, a
ValueErroris raised.
_ingest_edge_list(df, G, default_slice, default_directed, default_weight)
Parse edge-list-like tables (incl. COO/DOK).
_ingest_hyperedge(df, G, default_slice, default_weight)
Parse hyperedge tables (members OR head/tail).
_ingest_incidence(df, G, default_slice, default_weight)
Parse incidence matrices (first col = entity id, remaining numeric edge columns).
_ingest_adjacency(df, G, default_slice, default_directed, default_weight)
Parse adjacency matrices (square). If first column is non-numeric, treat as row labels.
_ingest_lil(df, G, default_slice, default_directed, default_weight)
Parse LIL-style neighbor tables: one row per vertex with a neighbors column.
Internal helpers
This module purposefully avoids importing stdlib csv and uses Polars for IO.
It ingests a CSV into AnnNet by auto-detecting common schemas: - Edge list (including DOK/COO triples and variations) - Hyperedge table (members column or head/tail sets) - Incidence matrix (rows=entities, cols=edges, ±w orientation) - Adjacency matrix (square matrix, weighted/unweighted) - LIL-style neighbor lists (single column of neighbors)
If auto-detection fails or you want control, pass schema=... explicitly.
Dependencies: polars, numpy, scipy (only if you use sparse helpers), AnnNet
Design notes:
- We treat unknown columns as attributes ("pure" non-structural) and write them via
the corresponding set_*_attrs APIs when applicable.
- slices: if a slice column exists it can contain a single slice or multiple
(separated by |, ;, or ,). Per-slice weight overrides support columns of the
form weight:<slice_name>.
- Directedness: we honor an explicit directed column when present (truthy), else
infer for incidence (presence of negative values) and adjacency (symmetry check).
- We try not to guess too hard. If the heuristics get it wrong, supply
schema="edge_list" / "hyperedge" / "incidence" / "adjacency" / "lil".
Public entry points: - load_csv_to_graph(path, graph=None, schema="auto", options) -> AnnNet - from_dataframe(df, graph=None, schema="auto", options) -> AnnNet
Both will create and return an AnnNet (or mutate the provided one).
Attributes
_STR_TRUE = {'1', 'true', 't', 'yes', 'y', 'on'}
module-attribute
_STR_FALSE = {'0', 'false', 'f', 'no', 'n', 'off'}
module-attribute
_slice_SEP = re.compile('[|;,]')
module-attribute
_SET_SEP = re.compile('[|;,]\\s*')
module-attribute
SRC_COLS = ['source', 'src', 'from', 'u']
module-attribute
DST_COLS = ['target', 'dst', 'to', 'v']
module-attribute
WGT_COLS = ['weight', 'w']
module-attribute
DIR_COLS = ['directed', 'is_directed', 'dir', 'orientation']
module-attribute
slice_COLS = ['slice', 'slices']
module-attribute
EDGE_ID_COLS = ['edge', 'edge_id', 'id']
module-attribute
vertex_ID_COLS = ['vertex', 'vertex_id', 'id', 'name', 'label']
module-attribute
NEIGH_COLS = ['neighbors', 'nbrs', 'adj', 'adjacency', 'neighbors_out', 'neighbors_in']
module-attribute
MEMBERS_COLS = ['members', 'verts', 'participants']
module-attribute
HEAD_COLS = ['head', 'heads']
module-attribute
TAIL_COLS = ['tail', 'tails']
module-attribute
ROW_COLS = ['row', 'i', 'r']
module-attribute
COL_COLS = ['col', 'column', 'j', 'c']
module-attribute
VAL_COLS = ['val', 'value', 'w', 'weight']
module-attribute
RESERVED = set(SRC_COLS + DST_COLS + WGT_COLS + DIR_COLS + slice_COLS + EDGE_ID_COLS + vertex_ID_COLS + NEIGH_COLS + MEMBERS_COLS + HEAD_COLS + TAIL_COLS + ROW_COLS + COL_COLS + VAL_COLS)
module-attribute
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
_norm(s)
_truthy(x)
_split_slices(cell)
_split_set(cell)
_pick_first(df, candidates)
_is_numeric_series(s)
_attr_columns(df, exclude)
_detect_schema(df)
load_csv_to_graph(path, *, graph=None, schema='auto', default_slice=None, default_directed=None, default_weight=1.0, infer_schema_length=10000, encoding=None, null_values=None, low_memory=True, **kwargs)
Load a CSV and construct/augment an AnnNet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the CSV file. |
required |
graph
|
AnnNet or None
|
If provided, mutate this graph; otherwise create a new AnnNet using
|
None
|
schema
|
('auto', 'edge_list', 'hyperedge', 'incidence', 'adjacency', 'lil')
|
Parsing mode. 'auto' tries to infer the schema from columns and types. |
'auto','edge_list','hyperedge','incidence','adjacency','lil'
|
default_slice
|
str or None
|
slice to register vertices/edges when none is specified in the data. |
None
|
default_directed
|
bool or None
|
Default directedness for binary edges when not implied by data. |
None
|
default_weight
|
float
|
Default weight when not specified. |
1.0
|
infer_schema_length
|
int
|
Row count Polars uses to infer column types. |
10000
|
encoding
|
str or None
|
File encoding override. |
None
|
null_values
|
list[str] or None
|
Additional strings to interpret as nulls. |
None
|
low_memory
|
bool
|
Pass to Polars read_csv for balanced memory usage. |
True
|
**kwargs
|
Any
|
Passed to AnnNet constructor if |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
The populated graph instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no AnnNet can be constructed or imported. |
ValueError
|
If schema is unknown or parsing fails. |
from_dataframe(df, *, graph=None, schema='auto', default_slice=None, default_directed=None, default_weight=1.0, **kwargs)
Build/augment an AnnNet from a Polars DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input table parsed from CSV. |
required |
graph
|
AnnNet or None
|
If provided, mutate this graph; otherwise create a new AnnNet using
|
None
|
schema
|
('auto', 'edge_list', 'hyperedge', 'incidence', 'adjacency', 'lil')
|
Parsing mode. 'auto' tries to infer the schema. |
'auto','edge_list','hyperedge','incidence','adjacency','lil'
|
default_slice
|
str or None
|
Fallback slice if no slice is specified in the data. |
None
|
default_directed
|
bool or None
|
Default directedness for binary edges when not implied by data. |
None
|
default_weight
|
float
|
Weight to use when no explicit weight is present. |
1.0
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
The populated graph instance. |
export_edge_list_csv(G, path, slice=None)
Export the binary edge subgraph to a CSV [Comma-Separated Values] file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
AnnNet instance to export. Must support |
required |
path
|
str or Path
|
Output path for the CSV file. |
required |
slice
|
str
|
Restrict the export to a specific slice. If None, all slices are exported. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
- Only binary edges are exported. Hyperedges (edges connecting more than two entities) are ignored.
- Output columns include: 'source', 'target', 'weight', 'directed', and 'slice'.
- If a weight column does not exist, a default weight of 1.0 is written.
- If a directedness column is absent, it will be written as
None. - This format is compatible with
load_csv_to_graph(schema="edge_list").
export_hyperedge_csv(G, path, slice=None, directed=None)
Export hyperedges from the graph to a CSV [Comma-Separated Values] file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
AnnNet
|
AnnNet instance to export. Must support |
required |
path
|
str or Path
|
Output path for the CSV file. |
required |
slice
|
str
|
Restrict the export to a specific slice. If None, all slices are exported. |
None
|
directed
|
bool
|
Force treatment of hyperedges as directed or undirected. If None, the function attempts to infer directedness from the graph. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
- If the graph exposes a 'members' column, the output will contain one row per undirected hyperedge.
- If 'head' and 'tail' columns are present, the output will contain one row per
directed hyperedge. If
directed=Falseis passed, 'head' and 'tail' are merged into a 'members' column. - A 'weight' column is included if available; otherwise, all weights default to 1.0.
- A 'slice' column is included if present or if
sliceis specified. - This format is compatible with
load_csv_to_graph(schema="hyperedge"). - If the graph does not expose hyperedge columns, a
ValueErroris raised.
_ingest_edge_list(df, G, default_slice, default_directed, default_weight)
Parse edge-list-like tables (incl. COO/DOK).
_ingest_hyperedge(df, G, default_slice, default_weight)
Parse hyperedge tables (members OR head/tail).
_ingest_incidence(df, G, default_slice, default_weight)
Parse incidence matrices (first col = entity id, remaining numeric edge columns).
_ingest_adjacency(df, G, default_slice, default_directed, default_weight)
Parse adjacency matrices (square). If first column is non-numeric, treat as row labels.
_ingest_lil(df, G, default_slice, default_directed, default_weight)
Parse LIL-style neighbor tables: one row per vertex with a neighbors column.
Excel
annnet.io.excel
Functions
load_excel_to_graph(path, graph=None, schema='auto', sheet=None, default_slice=None, default_directed=None, default_weight=1.0, **kwargs)
Load an Excel (.xlsx/.xls) file by converting it internally to CSV, then building a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
Path to the Excel file. |
required |
graph
|
AnnNet
|
Existing graph instance. If None, a new one is created. |
None
|
schema
|
('auto', 'edge_list', 'hyperedge', 'incidence', 'adjacency', 'lil')
|
AnnNet schema to assume or infer. |
'auto'
|
sheet
|
str
|
Sheet name to load. Defaults to the first sheet. |
None
|
default_slice
|
str
|
Default slice name if not present. |
None
|
default_directed
|
bool
|
Default directedness if not present or inferrable. |
None
|
default_weight
|
float
|
Default weight if no weight column exists. |
1.0
|
**kwargs
|
Extra keyword arguments passed to the graph constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
The created or augmented graph. |
Notes
- This function does not require
fastexceloropenpyxl. - The Excel is read once into memory and written to a temporary CSV, then processed with the CSV loader.
- Supported formats and schemas are identical to
load_csv_to_graph.
Internal helpers
Functions
load_excel_to_graph(path, graph=None, schema='auto', sheet=None, default_slice=None, default_directed=None, default_weight=1.0, **kwargs)
Load an Excel (.xlsx/.xls) file by converting it internally to CSV, then building a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
Path to the Excel file. |
required |
graph
|
AnnNet
|
Existing graph instance. If None, a new one is created. |
None
|
schema
|
('auto', 'edge_list', 'hyperedge', 'incidence', 'adjacency', 'lil')
|
AnnNet schema to assume or infer. |
'auto'
|
sheet
|
str
|
Sheet name to load. Defaults to the first sheet. |
None
|
default_slice
|
str
|
Default slice name if not present. |
None
|
default_directed
|
bool
|
Default directedness if not present or inferrable. |
None
|
default_weight
|
float
|
Default weight if no weight column exists. |
1.0
|
**kwargs
|
Extra keyword arguments passed to the graph constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
The created or augmented graph. |
Notes
- This function does not require
fastexceloropenpyxl. - The Excel is read once into memory and written to a temporary CSV, then processed with the CSV loader.
- Supported formats and schemas are identical to
load_csv_to_graph.
DataFrames (Polars/Pandas/Narwhals)
annnet.io.dataframe_io
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Attributes
V
property
All vertices as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Vertex IDs. |
E
property
All edges as a tuple.
Returns:
| Type | Description |
|---|---|
tuple
|
Edge identifiers. |
num_vertices
property
Total number of vertices in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
num_edges
property
Total number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
nv
property
Shorthand for num_vertices.
Returns:
| Type | Description |
|---|---|
int
|
|
ne
property
Shorthand for num_edges.
Returns:
| Type | Description |
|---|---|
int
|
|
shape
property
AnnNet shape as a tuple: (num_vertices, num_edges).
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
nx
property
ig
property
gt
property
obs
property
Vertex attribute table (observations).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
var
property
Edge attribute table (variables).
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
uns
property
Unstructured metadata.
Returns:
| Type | Description |
|---|---|
dict
|
|
slices
property
layers
property
idx
property
cache
property
Functions
add_vertex(vertex_id, slice=None, layer=None, **attributes)
Add (or upsert) a vertex and optionally attach it to a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier (unique across entities). |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
layer
|
str
|
Layer label (used only in single-aspect mode). |
None
|
**attributes
|
Vertex attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID (echoed). |
Notes
Ensures a row exists in the vertex attribute table and resizes the incidence matrix if needed.
add_vertices(vertices, slice=None, **attributes)
Add multiple vertices in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. Each item can be:
- |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
**attributes
|
Attributes applied to all vertices (merged with per-vertex attrs). |
{}
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The vertex IDs added (in input order). |
add_edge_entity(edge_entity_id, slice=None, **attributes)
Register a connectable edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_entity_id
|
str
|
Identifier for the edge-entity. |
required |
slice
|
str
|
Slice to place the edge-entity into. Defaults to the active slice. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge-entity ID. |
Notes
Deprecated: prefer add_edge(..., as_entity=True).
add_edge(source, target, slice=None, weight=1.0, edge_id=None, as_entity=False, propagate='none', slice_weight=None, directed=None, edge_directed=None, **attributes)
Add or update a binary edge between two entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID (vertex or edge entity). |
required |
target
|
str
|
Target entity ID (vertex or edge entity). |
required |
slice
|
str
|
Slice to place the edge into. Defaults to the active slice. |
None
|
weight
|
float
|
Global edge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
as_entity
|
bool
|
If True, this edge can be an endpoint of other edges. |
False
|
propagate
|
(none, shared, all)
|
Slice propagation mode. |
'none'
|
slice_weight
|
float
|
Per-slice weight override for this edge. |
None
|
directed
|
bool
|
Global directedness override (legacy). |
None
|
edge_directed
|
bool
|
Per-edge directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The edge ID (new or updated). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
Directed edges write +weight at source and -weight at target.
Undirected edges write +weight at both endpoints.
add_parallel_edge(source, target, weight=1.0, **attributes)
Add a parallel edge (same endpoints, different ID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
weight
|
float
|
Edge weight stored in the incidence column. |
1.0
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The new edge ID. |
add_hyperedge(*, members=None, head=None, tail=None, slice=None, weight=1.0, edge_id=None, edge_directed=None, **attributes)
Create a k-ary hyperedge as a single incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
members
|
Iterable[str]
|
Undirected members (>= 2). Each member gets |
None
|
head
|
Iterable[str]
|
Directed head set (sources). Each head gets |
None
|
tail
|
Iterable[str]
|
Directed tail set (targets). Each tail gets |
None
|
slice
|
str
|
Slice to place the hyperedge into. Defaults to the active slice. |
None
|
weight
|
float
|
Hyperedge weight stored in the incidence column. |
1.0
|
edge_id
|
str
|
Explicit edge ID. If omitted, a fresh ID is generated. |
None
|
edge_directed
|
bool
|
Explicit directedness override. |
None
|
**attributes
|
Edge attributes to upsert. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The hyperedge ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If members/head/tail are inconsistent or invalid. |
set_hyperedge_coeffs(edge_id, coeffs)
Write per-vertex coefficients into the incidence column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Hyperedge ID to update. |
required |
coeffs
|
dict[str, float]
|
Mapping of vertex ID to coefficient value. |
required |
add_edge_to_slice(lid, eid)
Attach an existing edge to a slice (no weight changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lid
|
str
|
Slice ID. |
required |
eid
|
str
|
Edge ID. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
make_undirected(*, drop_flexible=True, update_default=True)
Force the whole graph to be undirected in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_flexible
|
bool
|
If True, clear flexible-direction policies. |
True
|
update_default
|
bool
|
If True, set the graph default to undirected for future edges. |
True
|
Notes
Binary edges are rewritten to (+w, +w) at (source, target).
Hyperedges are rewritten to +w on all members.
remove_edge(edge_id)
Remove an edge (binary or hyperedge) from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
Notes
Physically removes the incidence column (no CSR round-trip) and cleans edge attributes and slice memberships.
remove_vertex(vertex_id)
Remove a vertex and all incident edges (binary + hyperedges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the vertex is not found. |
Notes
Rebuilds entity indexing and shrinks the incidence matrix accordingly.
remove_slice(slice_id)
Remove a non-default slice and its per-slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If attempting to remove the internal default slice. |
KeyError
|
If the slice does not exist. |
Notes
Does not delete vertices or edges globally; only membership and metadata.
get_vertex(index)
Return the vertex ID corresponding to a given internal index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Internal vertex index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The vertex ID. |
get_edge(index)
Return edge endpoints in a canonical form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | str
|
Internal edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
tuple[frozenset, frozenset]
|
|
incident_edges(vertex_id)
Return all edge indices incident to a given vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Edge indices incident to the vertex. |
has_edge(source=None, target=None, edge_id=None)
Check edge existence using one of three modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
None
|
target
|
str
|
Target entity ID. |
None
|
edge_id
|
str
|
Edge identifier. |
None
|
Returns:
| Type | Description |
|---|---|
bool | tuple[bool, list[str]]
|
One of:
- bool, if only |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the argument combination is invalid. |
has_vertex(vertex_id)
Test for the existence of a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the vertex exists. |
get_edge_ids(source, target)
List all edge IDs between two endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source entity ID. |
required |
target
|
str
|
Target entity ID. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs (may be empty). |
degree(entity_id)
Degree of a vertex or edge-entity (number of incident non-zero entries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Degree of the entity. |
vertices()
Get all vertex IDs (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
list[str]
|
Vertex IDs. |
edges()
Get all edge IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs. |
edge_list()
Materialize (source, target, edge_id, weight) for binary/vertex-edge edges.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str, float]]
|
Tuples of |
get_directed_edges()
List IDs of directed edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Directed edge IDs. |
get_undirected_edges()
List IDs of undirected edges.
Returns:
| Type | Description |
|---|---|
list[str]
|
Undirected edge IDs. |
number_of_vertices()
Count vertices (excluding edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
Number of vertices. |
number_of_edges()
Count edges (columns in the incidence matrix).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges. |
global_entity_count()
Count unique entities present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of entities across slices. |
global_edge_count()
Count unique edges present across all slices (union of memberships).
Returns:
| Type | Description |
|---|---|
int
|
Number of edges across slices. |
in_edges(vertices)
Iterate over all edges that are incoming to one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose target set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
in_edges() and out_edges().
out_edges(vertices)
Iterate over all edges that are outgoing from one or more vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str]
|
Vertex ID or iterable of vertex IDs. All edges whose source set intersects with this set will be yielded. |
required |
Yields:
| Type | Description |
|---|---|
tuple[int, tuple[frozenset, frozenset]]
|
|
Notes
Works with binary and hyperedges. Undirected edges appear in both
out_edges() and in_edges().
get_or_create_vertex_by_attrs(slice=None, **attrs)
Return vertex ID for the given composite-key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice to place a newly created vertex into. |
None
|
**attrs
|
Attributes used to build the composite key. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Vertex ID matching the composite key. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no composite key fields are configured. |
ValueError
|
If required key fields are missing. |
Notes
Requires set_vertex_key(...) to have been called.
vertex_key_tuple(vertex_id)
Return the composite-key tuple for a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
tuple | None
|
Composite key tuple, or None if incomplete or not configured. |
X()
Sparse incidence matrix.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
write(path, **kwargs)
Save to .annnet format (zero loss).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**kwargs
|
Passed to |
{}
|
read(path, **kwargs)
classmethod
Load from .annnet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
**kwargs
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
|
view(vertices=None, edges=None, slices=None, predicate=None)
Create a lazy view/subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex IDs to include. |
None
|
edges
|
Iterable[str]
|
Edge IDs to include. |
None
|
slices
|
Iterable[str]
|
Slice IDs to include. |
None
|
predicate
|
callable
|
Predicate applied to vertices/edges for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
snapshot(label=None)
Create a named snapshot of current graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable label for the snapshot. Auto-generated if None. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Snapshot metadata. |
diff(a, b=None)
Compare two snapshots or compare snapshot with current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str | dict | AnnNet
|
First snapshot (label, snapshot dict, or AnnNet instance). |
required |
b
|
str | dict | AnnNet | None
|
Second snapshot. If None, compare with current state. |
None
|
Returns:
| Type | Description |
|---|---|
GraphDiff
|
Difference object with added/removed entities. |
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Functions
to_dataframes(graph, *, include_slices=True, include_hyperedges=True, explode_hyperedges=False, public_only=True)
Export graph to Polars DataFrames.
Returns a dictionary of DataFrames representing different aspects of the graph: - 'nodes': Vertex IDs and attributes - 'edges': Binary edges with source, target, weight, directed, attributes - 'hyperedges': Hyperedges with head/tail sets (if include_hyperedges=True) - 'slices': slice membership (if include_slices=True) - 'slice_weights': Per-slice edge weights (if include_slices=True)
Note: Output is always Polars because hyperedges use List types which aren't universally supported across dataframe libraries.
Args: graph: AnnNet instance to export include_slices: Include slice membership tables include_hyperedges: Include hyperedge table explode_hyperedges: If True, explode hyperedges to one row per endpoint public_only: If True, filter out attributes starting with '__'
Returns: Dictionary mapping table names to Polars DataFrames
_to_dicts(df)
Convert narwhals DataFrame to list of dicts.
_get_height(df)
Get row count from narwhals DataFrame.
from_dataframes(nodes=None, edges=None, hyperedges=None, slices=None, slice_weights=None, *, directed=None, exploded_hyperedges=False)
Import graph from any DataFrame (Pandas, Polars, PyArrow, etc.).
Accepts DataFrames in the format produced by to_dataframes():
Nodes DataFrame (optional): - Required: vertex_id - Optional: any attribute columns
Edges DataFrame (optional): - Required: source, target - Optional: edge_id, weight, directed, edge_type, attribute columns
Hyperedges DataFrame (optional): - Compact format: edge_id, directed, weight, head (list), tail (list), members (list) - Exploded format: edge_id, vertex_id, role, weight, directed
slices DataFrame (optional): - Required: slice_id, edge_id
slice_weights DataFrame (optional): - Required: slice_id, edge_id, weight
Args: nodes: DataFrame with vertex_id and attributes (Pandas/Polars/PyArrow/etc.) edges: DataFrame with binary edges hyperedges: DataFrame with hyperedges slices: DataFrame with slice membership slice_weights: DataFrame with per-slice edge weights directed: Default directedness (None = mixed graph) exploded_hyperedges: If True, hyperedges DataFrame is in exploded format
Returns: AnnNet instance
Internal helpers
Classes
AnnNet
Sparse incidence-matrix graph with slices, attributes, parallel edges, and hyperedges.
The graph is backed by a DOK (Dictionary Of Keys) sparse matrix and exposes sliceed views and attribute tables stored as Polars DF (DataFrame). Supports: vertices, binary edges (directed/undirected), edge-entities (vertex-edge hybrids), k-ary hyperedges (directed/undirected), per-slice membership and weights, and Polars-backed attribute upserts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Whether edges are directed by default. Individual edges can override this. |
None
|
Notes
- Incidence columns encode orientation: +w on source/head, −w on target/tail for directed edges; +w on all members for undirected edges/hyperedges.
- Attributes are pure: structural keys are filtered out so attribute tables contain only user data.
See Also
add_vertex, add_edge, add_hyperedge, edges_view, vertices_view, slices_view
Functions
__init__(directed=None, n=0, e=0, annotations=None, annotations_backend='polars', **kwargs)
Initialize an empty incidence-matrix graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directed
|
bool
|
Global default for edge directionality. Individual edges can override this. |
None
|
Notes
- Stores entities (vertices and edge-entities), edges (including parallels), and an incidence matrix in DOK (Dictionary Of Keys) sparse format.
- Attribute tables are Polars DF (DataFrame) with canonical key columns:
vertex_attributes(vertex_id),edge_attributes(edge_id),slice_attributes(slice_id), andedge_slice_attributes(slice_id, edge_id, weight). - A
'default'slice is created and set active.
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
_propagate_to_shared_slices(edge_id, source, target)
INTERNAL: Add an edge to all slices that already contain both endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_propagate_to_all_slices(edge_id, source, target)
INTERNAL: Add an edge to any slice containing either endpoint and insert the missing endpoint into that slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
source
|
str
|
|
required |
target
|
str
|
|
required |
_normalize_vertices_arg(vertices)
Normalize a single vertex or an iterable of vertices into a set.
This internal utility function standardizes input for methods like
in_edges() and out_edges() by converting the argument into a set
of vertex identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
str | Iterable[str] | None
|
|
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of vertex identifiers. If |
Notes
- Strings are treated as single vertex IDs, not iterables.
- If the argument is neither iterable nor a string, it is wrapped in a set.
- Used internally by API methods that accept flexible vertex arguments.
_is_directed_edge(edge_id)
Check if an edge is directed (per-edge flag overrides graph default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
Functions
to_dataframes(graph, *, include_slices=True, include_hyperedges=True, explode_hyperedges=False, public_only=True)
Export graph to Polars DataFrames.
Returns a dictionary of DataFrames representing different aspects of the graph: - 'nodes': Vertex IDs and attributes - 'edges': Binary edges with source, target, weight, directed, attributes - 'hyperedges': Hyperedges with head/tail sets (if include_hyperedges=True) - 'slices': slice membership (if include_slices=True) - 'slice_weights': Per-slice edge weights (if include_slices=True)
Note: Output is always Polars because hyperedges use List types which aren't universally supported across dataframe libraries.
Args: graph: AnnNet instance to export include_slices: Include slice membership tables include_hyperedges: Include hyperedge table explode_hyperedges: If True, explode hyperedges to one row per endpoint public_only: If True, filter out attributes starting with '__'
Returns: Dictionary mapping table names to Polars DataFrames
_to_dicts(df)
Convert narwhals DataFrame to list of dicts.
_get_height(df)
Get row count from narwhals DataFrame.
from_dataframes(nodes=None, edges=None, hyperedges=None, slices=None, slice_weights=None, *, directed=None, exploded_hyperedges=False)
Import graph from any DataFrame (Pandas, Polars, PyArrow, etc.).
Accepts DataFrames in the format produced by to_dataframes():
Nodes DataFrame (optional): - Required: vertex_id - Optional: any attribute columns
Edges DataFrame (optional): - Required: source, target - Optional: edge_id, weight, directed, edge_type, attribute columns
Hyperedges DataFrame (optional): - Compact format: edge_id, directed, weight, head (list), tail (list), members (list) - Exploded format: edge_id, vertex_id, role, weight, directed
slices DataFrame (optional): - Required: slice_id, edge_id
slice_weights DataFrame (optional): - Required: slice_id, edge_id, weight
Args: nodes: DataFrame with vertex_id and attributes (Pandas/Polars/PyArrow/etc.) edges: DataFrame with binary edges hyperedges: DataFrame with hyperedges slices: DataFrame with slice membership slice_weights: DataFrame with per-slice edge weights directed: Default directedness (None = mixed graph) exploded_hyperedges: If True, hyperedges DataFrame is in exploded format
Returns: AnnNet instance