Skip to content

Graph

Primary graph objects from annnet.core.graph.

The main graph API centers on AnnNet/Graph, bulk vertex and edge construction with add_vertices and add_edges, graph-owned accessors (slices, layers, attrs, views, ops, idx, cache), annotation tables (obs, var, uns), and backend accessors (nx, ig, gt).

AnnNet

annnet.core.graph.AnnNet

Incidence-based graph with slices, multilayer coordinates, and rich edge types.

AnnNet stores topology in a sparse incidence matrix backed by canonical entity and edge registries. A row represents an entity, typically a vertex or an edge-entity, and a column represents an edge. The class supports:

  • binary directed and undirected edges
  • hyperedges, including directed head/tail hyperedges
  • edge-entities that can themselves participate as endpoints
  • slice membership and per-slice edge weights
  • optional multilayer coordinates on vertices and edges
  • dataframe-backed attribute storage

Parameters:

Name Type Description Default
directed bool | None

Default directedness for newly created binary edges. If None, methods fall back to directed semantics unless a per-edge flag is set.

None
v int

Initial row capacity for the incidence matrix.

0
e int

Initial column capacity for the incidence matrix.

0
annotations dict | None

Pre-built annotation tables to use instead of creating empty tables.

None
annotations_backend (auto, polars, pandas, pyarrow)

Preferred backend for newly initialized annotation tables. "auto" prefers Polars, then pandas, then PyArrow. None uses AnnNet's configured dataframe default.

"auto"
aspects dict[str, list[str]] | None

Initial multilayer aspect declaration. If omitted, the graph starts flat with a single placeholder aspect "_".

None
**kwargs

Initial graph-level attributes stored in :attr:graph_attributes.

{}
Notes

Directed incidence columns use positive values for sources or heads and negative values for targets or tails. Undirected binary edges and undirected hyperedges use positive values for all incident entities.

See Also

add_vertex add_edge add_vertices_bulk add_edges_bulk view

Attributes

num_vertices property
num_vertices

Alias for nv.

num_edges property
num_edges

Alias for ne.

nv property
nv

Total number of vertices in the graph.

ne property
ne

Total number of edges in the graph.

shape property
shape

AnnNet shape as a tuple: (num_vertices, num_edges).

V property
V

All vertices as a tuple.

Returns:

Type Description
tuple

Vertex IDs.

E property
E

All edges as a tuple.

Returns:

Type Description
tuple

Edge identifiers.

obs property
obs

Notebook-friendly vertex attribute table.

Returns:

Type Description
DataFrame - like
Notes

This is the quickest way to inspect vertex annotations in a notebook. It returns the underlying vertex-attribute table unchanged.

Examples:

>>> G = AnnNet()
>>> G.add_vertices([{'vertex_id': 'A', 'kind': 'gene'}])
>>> G.obs
>>> G.views.vertices()

Use :attr:obs when you want the raw vertex table directly. Use :attr:views when you want an explicit namespace for materialized tables.

var property
var

Notebook-friendly edge attribute table.

Returns:

Type Description
DataFrame - like
Notes

This is the direct edge-annotation table. It is often the most useful object to display in a notebook after edge insertion or IO.

Examples:

>>> G = AnnNet()
>>> G.add_vertices(['A', 'B'])
>>> G.add_edges([{'source': 'A', 'target': 'B', 'edge_id': 'e1'}])
>>> G.var
>>> G.views.edges()
uns property
uns

Unstructured metadata.

Returns:

Type Description
dict
attrs property
attrs

Attribute operations namespace.

Use this namespace for graph-, vertex-, edge-, and slice-level annotations.

Examples:

>>> G.attrs.set_vertex_attrs('A', symbol='TP53')
>>> G.attrs.get_vertex_attrs('A')
>>> G.attrs.set_edge_slice_attrs('baseline', 'e1', weight=0.5)
views property
views

Materialized table namespace.

This is the preferred namespace for notebook inspection and export of graph tables.

Examples:

>>> G.views.vertices()
>>> G.views.edges()
>>> G.views.slices()
>>> G.views.layers()
history instance-attribute
history = HistoryAccessor(self)
ops property
ops

Structural operations namespace.

Examples:

>>> H = G.ops.subgraph(['A', 'B', 'C'])
>>> M = G.ops.vertex_incidence_matrix(sparse=True)
>>> usage = G.ops.memory_usage()
layers property
layers

Layer operations namespace.

All multilayer configuration and layer-aware analysis lives here.

Examples:

>>> G.layers.set_aspects(['condition'], {'condition': ['ctrl', 'stim']})
>>> G.layers.list_layers()
>>> G.views.layers()
slices property
slices

Slice operations namespace.

Returns:

Type Description
SliceManager

Examples:

>>> G.slices.add_slice('baseline')
>>> G.slices.active = 'baseline'
>>> G.slices.list_slices()
idx property
idx

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

Returns:

Type Description
IndexManager
cache property
cache

Cache management (CSR/CSC materialization).

Returns:

Type Description
CacheManager
nx property
nx

Lazy NetworkX proxy.

Returns:

Type Description
_NXBackendAccessor

Proxy exposing NetworkX algorithms.

ig property
ig

Lazy igraph proxy.

Returns:

Type Description
_IGBackendAccessor

Proxy exposing igraph algorithms.

gt property
gt

Lazy graph-tool proxy.

Returns:

Type Description
_GTBackendAccessor

Proxy exposing graph-tool algorithms.

is_multilayer property
is_multilayer

True iff the graph has named aspects (is not a flat graph).

Functions

add_vertices
add_vertices(
    vertices, slice=None, layer=None, **attributes
)

Canonical public entry point for vertex insertion.

Accepts either a single vertex spec or an iterable of vertex specs.

add_edges
add_edges(*args, **kwargs)

Canonical public entry point for edge insertion.

Accepts either a single edge spec or an iterable of edge specs.

remove_vertices
remove_vertices(vertex_ids)

Remove many vertices (and their incident edges) in one pass.

Parameters:

Name Type Description Default
vertex_ids Iterable[str]

Vertex identifiers to remove.

required
remove_edges
remove_edges(edge_ids)

Remove many edges in one pass.

Parameters:

Name Type Description Default
edge_ids Iterable[str]

Edge identifiers to remove.

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

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

vertices
vertices()

Get all vertex IDs (excluding edge-entities).

Returns:

Type Description
list[str]

Vertex IDs.

edges
edges()

Get all edge IDs.

Returns:

Type Description
list[str]

Edge IDs.

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

incident_edges
incident_edges(vertices, direction='both')

Iterate over edges incident to one or more vertices.

Parameters:

Name Type Description Default
vertices str | Iterable[str]

One vertex identifier or an iterable of identifiers.

required
direction ('in', out, both)

Directional filter applied to binary edges. Undirected edges are yielded for both directions.

"in"

Yields:

Type Description
tuple[int, tuple]

Pairs of (column_index, edge_tuple) as returned by :meth:get_edge.

number_of_vertices
number_of_vertices()

Number of vertices. Prefer the nv property.

number_of_edges
number_of_edges()

Number of edges. Prefer the ne property.

read classmethod
read(path, **kwargs)

Read a graph from the native .annnet format.

Parameters:

Name Type Description Default
path str | Path

Input file path.

required
**kwargs

Passed to annnet.io.annnet_format.read.

{}

Returns:

Type Description
AnnNet
write
write(path, **kwargs)

Write the graph to the native .annnet format.

Parameters:

Name Type Description Default
path str | Path

Output file path.

required
**kwargs

Passed to annnet.io.annnet_format.write.

{}
view
view(
    vertices=None, edges=None, slices=None, predicate=None
)

Create a lazy graph view.

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 used for additional filtering.

None

Returns:

Type Description
GraphView
global_count
global_count(kind)

Count unique members across all slices.

Parameters:

Name Type Description Default
kind (vertices, edges, entities)

Membership domain to count.

"vertices"

Returns:

Type Description
int

Number of unique members observed across all slices.

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

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

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

X
X()

Sparse incidence matrix.

Returns:

Type Description
dok_matrix

EdgeType

annnet.core.graph.EdgeType