Skip to content

Graph

Primary graph objects from annnet.core.graph.

AnnNet

annnet.core.graph.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

Lazy NetworkX proxy.

Returns:

Type Description
_LazyNXProxy

Proxy exposing NetworkX algorithms.

ig property

Lazy igraph proxy.

Returns:

Type Description
_LazyIGProxy

Proxy exposing igraph algorithms.

gt property

Lazy graph-tool proxy.

Returns:

Type Description
_LazyGTProxy

Proxy exposing graph-tool algorithms.

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

Slice operations manager.

Returns:

Type Description
SliceManager
layers property

Layer operations manager.

Returns:

Type Description
LayerManager
idx property

Index lookups (entity_id<->row, edge_id<->col).

Returns:

Type Description
IndexManager
cache property

Cache management (CSR/CSC materialization).

Returns:

Type Description
CacheManager

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), and edge_slice_attributes(slice_id, edge_id, weight).
  • A 'default' slice is created and set active.
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: - vertex_id (str) - (vertex_id, attrs) tuple - dict containing vertex_id plus attributes

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 propagate is invalid.

TypeError

If weight is not numeric.

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

None
head Iterable[str]

Directed head set (sources). Each head gets +weight.

None
tail Iterable[str]

Directed tail set (targets). Each tail gets -weight.

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.

remove_orphans()

Remove all vertices with no incident edges from the AnnNet graph.

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]

(S, T) where S and T are frozensets of vertex IDs.

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 edge_id is provided. - (bool, [edge_ids...]) if source and target are provided.

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 (source, target, edge_id, weight).

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_vertex_count()

Count unique vertices present across all slices (union of memberships).

Returns:

Type Description
int

Number of vertices across slices.

global_entity_count()

Count unique entities present across all slices (vertices + edge-entities).

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

(edge_index, (S, T)) where S is sources/heads and T is targets/tails.

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

(edge_index, (S, T)) where S is sources/heads and T is targets/tails.

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 annnet.io.io_annnet.write.

{}
read(path, **kwargs) classmethod

Load from .annnet format.

Parameters:

Name Type Description Default
path str | Path

Input file path.

required
**kwargs

Passed to annnet.io.io_annnet.read.

{}

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.

EdgeType

annnet.core.graph.EdgeType