AnnNet Core + Attributes
The AnnNet class is the primary annotated network object. It composes
multiple mixins that provide topology management, attribute tables, bulk
operations, history, and cache control.
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
directed = directed
instance-attribute
_vertex_RESERVED = set(_vertex_RESERVED)
instance-attribute
_EDGE_RESERVED = set(_EDGE_RESERVED)
instance-attribute
_slice_RESERVED = set(_slice_RESERVED)
instance-attribute
entity_to_idx = {}
instance-attribute
idx_to_entity = {}
instance-attribute
entity_types = {}
instance-attribute
edge_to_idx = {}
instance-attribute
idx_to_edge = {}
instance-attribute
edge_definitions = {}
instance-attribute
edge_weights = {}
instance-attribute
edge_directed = {}
instance-attribute
edge_direction_policy = {}
instance-attribute
_vertex_key_fields = None
instance-attribute
_vertex_key_index = {}
instance-attribute
_num_entities = 0
instance-attribute
_num_edges = 0
instance-attribute
_annotations_backend = annotations_backend
instance-attribute
hyperedge_definitions = {}
instance-attribute
graph_attributes = {}
instance-attribute
_next_edge_id = 0
instance-attribute
_slices = {}
instance-attribute
_default_slice = 'default'
instance-attribute
slice_edge_weights = defaultdict(dict)
instance-attribute
_current_slice = self._default_slice
instance-attribute
_matrix = sp.dok_matrix((n, e), dtype=(np.float32))
instance-attribute
_grow_rows_to = _grow_rows_to
instance-attribute
_grow_cols_to = _grow_cols_to
instance-attribute
_history_enabled = True
instance-attribute
_history = []
instance-attribute
_version = 0
instance-attribute
_history_clock0 = time.perf_counter_ns()
instance-attribute
_snapshots = []
instance-attribute
aspects = []
instance-attribute
elem_layers = {}
instance-attribute
_all_layers = ()
instance-attribute
_V = set()
instance-attribute
_VM = set()
instance-attribute
vertex_aligned = False
instance-attribute
_nl_to_row = {}
instance-attribute
_row_to_nl = []
instance-attribute
_legacy_single_aspect_enabled = True
instance-attribute
edge_kind = {}
instance-attribute
edge_layers = {}
instance-attribute
_aspect_attrs = {}
instance-attribute
_layer_attrs = {}
instance-attribute
_vertex_layer_attrs = {}
instance-attribute
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
__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.
_init_annotation_tables(annotations)
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).
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
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. |
_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.
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. |
_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
|
|
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. |
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Edge Types
annnet.core.graph.EdgeType
Topology & Indexing
annnet.core._Index.IndexManager
Namespace for index operations. Provides clean API over existing dicts.
Attributes
_G = graph
instance-attribute
Functions
__init__(graph)
entity_to_row(entity_id)
Map an entity ID to its matrix row index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Row index for the entity. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the entity is not found. |
row_to_entity(row)
Map a matrix row index to its entity ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
int
|
Row index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Entity identifier. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the row index is not found. |
entities_to_rows(entity_ids)
Batch convert entity IDs to row indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_ids
|
Iterable[str]
|
Entity identifiers. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
|
rows_to_entities(rows)
Batch convert row indices to entity IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
Iterable[int]
|
Row indices. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
|
edge_to_col(edge_id)
Map an edge ID to its matrix column index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Column index for the edge. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
col_to_edge(col)
Map a matrix column index to its edge ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
int
|
Column index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Edge identifier. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the column index is not found. |
edges_to_cols(edge_ids)
Batch convert edge IDs to column indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_ids
|
Iterable[str]
|
Edge identifiers. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
|
cols_to_edges(cols)
Batch convert column indices to edge IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
Iterable[int]
|
Column indices. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
|
entity_type(entity_id)
Get the entity type for an ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the entity is not found. |
is_vertex(entity_id)
Check whether an entity ID refers to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
is_edge_entity(entity_id)
Check whether an entity ID refers to an edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
has_entity(entity_id)
Check if an ID exists as any entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
has_vertex(vertex_id)
Check if an ID exists and is a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
has_edge_id(edge_id)
Check if an edge ID exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
edge_count()
Return the number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
entity_count()
Return the number of entities (vertices + edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
|
vertex_count()
Return the number of true vertices (excludes edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
|
stats()
Return index statistics for entities and edges.
Returns:
| Type | Description |
|---|---|
dict
|
|
annnet.core._Index.IndexMapping
Functions
_get_next_edge_id()
INTERNAL: Generate a unique edge ID for parallel edges.
Returns:
| Type | Description |
|---|---|
str
|
Fresh |
_ensure_vertex_table()
INTERNAL: Ensure the vertex attribute table exists with a canonical schema.
Notes
- Creates an empty Polars DF [DataFrame] with a single
Utf8vertex_idcolumn if missing or malformed.
_ensure_vertex_row(vertex_id)
INTERNAL: Ensure a row for vertex_id exists in the vertex attribute DF.
Notes
- Appends a new row with
vertex_idandNonefor other columns if absent. - Preserves existing schema and columns.
_vertex_key_enabled()
_build_key_from_attrs(attrs)
Return tuple of field values in declared order, or None if any missing.
_current_key_of_vertex(vertex_id)
Read the current key tuple of a vertex from vertex_attributes (None if incomplete).
_gen_vertex_id_from_key(key_tuple)
Deterministic, human-readable vertex_id from a composite key.
Attribute Tables
annnet.core._Annotation.AttributesClass
Functions
set_graph_attribute(key, value)
Set a graph-level attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute name. |
required |
value
|
Any
|
Attribute value. |
required |
get_graph_attribute(key, default=None)
Get a graph-level attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if the attribute is missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
set_vertex_attrs(vertex_id, **attrs)
Upsert pure vertex attributes (non-structural) into the vertex table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored. |
{}
|
set_vertex_attrs_bulk(updates)
Upsert vertex attributes in bulk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
updates
|
dict[str, dict] | Iterable[tuple[str, dict]]
|
Mapping or iterable of |
required |
get_attr_vertex(vertex_id, key, default=None)
Get a single vertex attribute (scalar) or default if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
get_vertex_attribute(vertex_id, attribute)
(Legacy alias) Get a single vertex attribute from the Polars DF [DataFrame].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
attribute
|
str or Enum
|
Column name or enum with |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
Scalar value if present, else None. |
See Also
get_attr_vertex
set_edge_attrs(edge_id, **attrs)
Upsert pure edge attributes (non-structural) into the edge DF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored. |
{}
|
set_edge_attrs_bulk(updates)
Upsert edge attributes in bulk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
updates
|
dict[str, dict] | Iterable[tuple[str, dict]]
|
Mapping or iterable of |
required |
get_attr_edge(edge_id, key, default=None)
Get a single edge attribute (scalar) or default if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
get_edge_attribute(edge_id, attribute)
(Legacy alias) Get a single edge attribute from the Polars DF [DataFrame].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
attribute
|
str or Enum
|
Column name or enum with |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
Scalar value if present, else None. |
See Also
get_attr_edge
set_slice_attrs(slice_id, **attrs)
Upsert pure slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored. |
{}
|
get_slice_attr(slice_id, key, default=None)
Get a single slice attribute (scalar) or default if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
set_edge_slice_attrs(slice_id, edge_id, **attrs)
Upsert per-slice attributes for a specific edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_id
|
str
|
Edge identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored except |
{}
|
get_edge_slice_attr(slice_id, edge_id, key, default=None)
Get a per-slice attribute for an edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_id
|
str
|
Edge identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
set_slice_edge_weight(slice_id, edge_id, weight)
Set a legacy per-slice weight override for an edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_id
|
str
|
Edge identifier. |
required |
weight
|
float
|
Weight override. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice or edge does not exist. |
See Also
get_effective_edge_weight
get_effective_edge_weight(edge_id, slice=None)
Resolve the effective weight for an edge, optionally within a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
slice
|
str
|
If provided, return the slice override if present; otherwise global weight. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Effective weight. |
audit_attributes()
Audit attribute tables for extra/missing rows and invalid edge-slice pairs.
Returns:
| Type | Description |
|---|---|
dict
|
Summary with keys:
- |
_dtype_for_value(v, *, prefer='polars')
INTERNAL: Infer an appropriate dtype class for value v.
- If Polars is available and prefer='polars', returns Polars dtype objects.
- Otherwise returns Narwhals dtype classes.
_is_null_dtype(dtype)
Check if a dtype represents a null/unknown type.
_ensure_attr_columns(df, attrs)
Create/align attribute columns and dtypes to accept attrs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoDataFrame
|
Existing attribute table (any supported backend). |
required |
attrs
|
dict
|
Incoming key/value pairs to upsert. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Narwhals DataFrame with columns added/cast so inserts/updates work. |
Notes
- New columns are created with the inferred dtype.
- If a column is Unknown (null-ish) and the incoming value is not, it is cast to the inferred dtype.
- If dtypes conflict, both sides upcast to String to avoid schema errors.
_sanitize_value_for_nw(v)
_is_binary_type(dt)
INTERNAL: Robustly identify binary types across backends.
_safe_nw_cast(column_expr, target_dtype)
INTERNAL: Attempt cast; fallback to String on engine rejection.
_upsert_row(df, idx, attrs)
_upsert_rows_bulk(df, updates)
_variables_watched_by_vertices()
_incident_flexible_edges(v)
_apply_flexible_direction(edge_id)
get_edge_attrs(edge)
Return the full attribute dict for a single edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge
|
int | str
|
Edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Attribute dictionary for that edge. Empty if not found. |
get_vertex_attrs(vertex)
Return the full attribute dict for a single vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex
|
str
|
Vertex ID. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Attribute dictionary for that vertex. Empty if not found. |
get_attr_edges(indexes=None)
Retrieve edge attributes as a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indexes
|
Iterable[int] | None
|
Edge indices to retrieve. If None, returns all edges. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, dict]
|
Mapping of |
get_attr_vertices(vertices=None)
Retrieve vertex (vertex) attributes as a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | None
|
Vertex IDs to retrieve. If None, returns all vertices. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, dict]
|
Mapping of |
get_attr_from_edges(key, default=None)
Extract a specific attribute column for all edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute column name to extract. |
required |
default
|
Any
|
Value to use if the column or value is missing. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Mapping of |
get_edges_by_attr(key, value)
Retrieve all edges where a given attribute equals a specific value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute column name to filter on. |
required |
value
|
Any
|
Value to match. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs where the attribute equals |
get_graph_attributes()
Return a shallow copy of the graph-level attributes dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Shallow copy of global graph metadata. |
Notes
Returned value is a shallow copy to prevent external mutation.
set_edge_slice_attrs_bulk(slice_id, items)
Upsert edge-slice attributes for a single slice in bulk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
items
|
Iterable[tuple[str, dict]] | dict[str, dict]
|
Iterable or mapping of |
required |
Bulk Operations
annnet.core._BulkOps.BulkOps
Functions
add_vertices_bulk(vertices, slice=None)
Bulk add vertices with a Polars fast path when available.
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
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
Falls back to Narwhals-based logic when Polars is unavailable.
add_vertices_bulk_nw(vertices, slice=None)
Bulk add vertices using Narwhals-compatible operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This path is slower than the Polars fast path but preserves behavior.
add_edges_bulk(edges, *, slice=None, default_weight=1.0, default_edge_type='regular', default_propagate='none', default_slice_weight=None, default_edge_directed=None)
Bulk add or update binary edges (and vertex-edge edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
Iterable
|
Each item can be:
- |
required |
slice
|
str
|
Default slice to place edges into. |
None
|
default_weight
|
float
|
Default weight for edges missing an explicit weight. |
1.0
|
default_edge_type
|
str
|
Default edge type when not provided. |
'regular'
|
default_propagate
|
(none, shared, all)
|
Default slice propagation mode. |
'none'
|
default_slice_weight
|
float
|
Default per-slice weight override. |
None
|
default_edge_directed
|
bool
|
Default per-edge directedness override. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs for created/updated edges. |
Notes
Behavior mirrors add_edge() but grows the matrix once to reduce overhead.
add_hyperedges_bulk(hyperedges, *, slice=None, default_weight=1.0, default_edge_directed=None)
Bulk add or update hyperedges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedges
|
Iterable[dict]
|
Each item can be:
- |
required |
slice
|
str
|
Default slice for hyperedges missing an explicit slice. |
None
|
default_weight
|
float
|
Default weight for hyperedges missing an explicit weight. |
1.0
|
default_edge_directed
|
bool
|
Default directedness override. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Hyperedge IDs for created/updated hyperedges. |
Notes
Behavior mirrors add_hyperedge() but grows the matrix once to reduce overhead.
add_edges_to_slice_bulk(slice_id, edge_ids)
Add many edges to a slice and attach all incident vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_ids
|
Iterable[str]
|
Edge identifiers to add. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
No weights are changed in this operation.
add_edge_entities_bulk(items, slice=None)
Bulk add edge-entities (vertex-edge hybrids).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable
|
Accepts:
- iterable of string IDs
- iterable of |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
Attribute inserts are batched for efficiency.
set_vertex_key(*fields)
Declare composite key fields and rebuild the uniqueness index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*fields
|
str
|
Ordered field names used to build a composite key. |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If duplicates exist among already-populated vertices. |
Notes
Vertices missing some key fields are skipped during indexing.
remove_edges(edge_ids)
Remove many edges in one pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_ids
|
Iterable[str]
|
Edge identifiers to remove. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This is faster than calling remove_edge in a loop.
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 |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This is faster than calling remove_vertex in a loop.
_remove_edges_bulk(edge_ids)
_remove_vertices_bulk(vertex_ids)
History
annnet.core._History.History
Functions
_utcnow_iso()
_jsonify(x)
_log_event(op, **fields)
_log_mutation(name=None)
_install_history_hooks()
history(as_df=False)
Return the append-only mutation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_df
|
bool
|
If True, return a DataFrame; otherwise return a list of dicts. |
False
|
Returns:
| Type | Description |
|---|---|
list[dict] | DataFrame
|
Event records including |
Notes
Ordering is guaranteed by version and mono_ns. The log is in-memory
until exported.
export_history(path)
Write the mutation history to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Output path. Supported extensions: |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of events written. Returns 0 if the history is empty. |
Raises:
| Type | Description |
|---|---|
OSError
|
If the file cannot be written. |
Notes
Unknown extensions default to Parquet by appending .parquet.
enable_history(flag=True)
Enable or disable in-memory mutation logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flag
|
bool
|
When True, start/continue logging; when False, pause logging. |
True
|
Returns:
| Type | Description |
|---|---|
None
|
|
clear_history()
Clear the in-memory mutation log.
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This does not delete any files previously exported.
mark(label)
Insert a manual marker into the mutation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable tag for the marker event. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
The event is recorded with op='mark' alongside standard fields
(version, ts_utc, mono_ns). Logging must be enabled for the
marker to be recorded.
annnet.core._History.GraphDiff
Represents the difference between two graph states.
Attributes:
| Name | Type | Description |
|---|---|---|
vertices_added |
set
|
Vertices in b but not in a |
vertices_removed |
set
|
Vertices in a but not in b |
edges_added |
set
|
Edges in b but not in a |
edges_removed |
set
|
Edges in a but not in b |
slices_added |
set
|
slices in b but not in a |
slices_removed |
set
|
slices in a but not in b |
Attributes
snapshot_a = snapshot_a
instance-attribute
snapshot_b = snapshot_b
instance-attribute
vertices_added = snapshot_b['vertex_ids'] - snapshot_a['vertex_ids']
instance-attribute
vertices_removed = snapshot_a['vertex_ids'] - snapshot_b['vertex_ids']
instance-attribute
edges_added = snapshot_b['edge_ids'] - snapshot_a['edge_ids']
instance-attribute
edges_removed = snapshot_a['edge_ids'] - snapshot_b['edge_ids']
instance-attribute
slices_added = snapshot_b['slice_ids'] - snapshot_a['slice_ids']
instance-attribute
slices_removed = snapshot_a['slice_ids'] - snapshot_b['slice_ids']
instance-attribute
Functions
__init__(snapshot_a, snapshot_b)
summary()
Return a human-readable summary of differences.
Returns:
| Type | Description |
|---|---|
str
|
Summary text describing added/removed vertices, edges, and slices. |
is_empty()
Check whether the diff contains no changes.
Returns:
| Type | Description |
|---|---|
bool
|
|
__repr__()
to_dict()
Convert the diff to a serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
|
Cache & Operations
annnet.core._Cache.CacheManager
Cache manager for materialized views (CSR/CSC).
Attributes
_G = graph
instance-attribute
_csr = None
instance-attribute
_csc = None
instance-attribute
_adjacency = None
instance-attribute
_csr_version = None
instance-attribute
_csc_version = None
instance-attribute
_adjacency_version = None
instance-attribute
csr
property
Return the CSR (Compressed Sparse Row) matrix.
Returns:
| Type | Description |
|---|---|
csr_matrix
|
|
Notes
Built and cached on first access.
csc
property
Return the CSC (Compressed Sparse Column) matrix.
Returns:
| Type | Description |
|---|---|
csc_matrix
|
|
Notes
Built and cached on first access.
adjacency
property
Return the adjacency matrix computed from incidence.
Returns:
| Type | Description |
|---|---|
spmatrix
|
|
Notes
For incidence matrix B, adjacency is computed as A = B @ B.T.
Functions
__init__(graph)
has_csr()
Check whether a valid CSR cache exists.
Returns:
| Type | Description |
|---|---|
bool
|
|
has_csc()
Check whether a valid CSC cache exists.
Returns:
| Type | Description |
|---|---|
bool
|
|
has_adjacency()
Check whether a valid adjacency cache exists.
Returns:
| Type | Description |
|---|---|
bool
|
|
get_csr()
Return the cached CSR matrix.
Returns:
| Type | Description |
|---|---|
csr_matrix
|
|
get_csc()
Return the cached CSC matrix.
Returns:
| Type | Description |
|---|---|
csc_matrix
|
|
get_adjacency()
Return the cached adjacency matrix.
Returns:
| Type | Description |
|---|---|
spmatrix
|
|
invalidate(formats=None)
Invalidate cached formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formats
|
list[str]
|
Formats to invalidate ( |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
build(formats=None)
Pre-build specified formats (eager caching).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formats
|
list[str]
|
Formats to build ( |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
clear()
Clear all caches.
Returns:
| Type | Description |
|---|---|
None
|
|
info()
Get cache status and memory usage.
Returns:
| Type | Description |
|---|---|
dict
|
Status and size information for each cached format. |
annnet.core._Cache.Operations
Functions
edge_subgraph(edges)
Create a subgraph containing only a specified subset of edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
Iterable[str] | Iterable[int]
|
Edge identifiers or edge indices to retain. |
required |
Returns:
| Type | Description |
|---|---|
AnnNet
|
Subgraph containing selected edges and their incident vertices. |
Notes
Hyperedges are supported and retain all member vertices.
subgraph(vertices)
Create a vertex-induced subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex identifiers to retain. |
required |
Returns:
| Type | Description |
|---|---|
AnnNet
|
Subgraph containing only the specified vertices and their internal edges. |
Notes
For hyperedges, all member vertices must be included to retain the edge.
extract_subgraph(vertices=None, edges=None)
Create a subgraph based on vertex and/or edge filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | None
|
Vertex IDs to include. If None, no vertex filtering is applied. |
None
|
edges
|
Iterable[str] | Iterable[int] | None
|
Edge IDs or indices to include. If None, no edge filtering is applied. |
None
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
Filtered subgraph. |
Notes
This is a convenience method that delegates to subgraph() and
edge_subgraph() internally.
reverse()
Return a new graph with all directed edges reversed.
Returns:
| Type | Description |
|---|---|
AnnNet
|
A new |
Behavior
- Binary edges: direction is flipped by swapping source and target.
- Directed hyperedges:
headandtailsets are swapped. - Undirected edges/hyperedges: unaffected.
- Edge attributes and metadata are preserved.
Notes
- This operation does not modify the original graph.
- If the graph is undirected (
self.directed == False), the result is identical to the original. - For mixed graphs (directed + undirected edges), only the directed ones are reversed.
subgraph_from_slice(slice_id, *, resolve_slice_weights=True)
Create a subgraph induced by a single slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
resolve_slice_weights
|
bool
|
If True, use per-slice edge weights when available. |
True
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
Subgraph containing the slice vertices and edges. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
_row_attrs(df, key_col, key)
INTERNAL: return a dict of attributes for the row in df where key_col == key,
excluding the key column itself. If not found or df empty, return {}.
Caches per (id(df), key_col) for speed; cache auto-refreshes when the df object changes.
copy(history=False)
Deep copy of the entire AnnNet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history
|
bool
|
If True, copy the mutation history and snapshot timeline. If False, the new graph starts with a clean history. |
False
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
A new graph with full structural and attribute fidelity. |
Notes
O(N) Python, O(nnz) matrix; this path is optimized for speed.
memory_usage()
Approximate total memory usage in bytes.
Returns:
| Type | Description |
|---|---|
int
|
Estimated bytes for the incidence matrix, dictionaries, and attribute DFs. |
get_vertex_incidence_matrix_as_lists(values=False)
Materialize the vertex–edge incidence structure as Python lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
(bool, optional(default=False))
|
|
False
|
Returns:
| Type | Description |
|---|---|
dict[str, list]
|
A mapping from |
Notes
- Internally uses the sparse incidence matrix
self._matrix, which is stored as a SciPy CSR (compressed sparse row) matrix or similar. - The incidence matrix
Mis defined as:- Rows: vertices
- Columns: edges
- Entry
M[i, j]non-zero ⇨ vertexiis incident to edgej.
- This is a convenient method when you want a native-Python structure for downstream use (e.g., exporting, iterating, or visualization).
vertex_incidence_matrix(values=False, sparse=False)
Return the vertex–edge incidence matrix in sparse or dense form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
(bool, optional(default=False))
|
If |
False
|
sparse
|
(bool, optional(default=False))
|
|
False
|
Returns:
| Type | Description |
|---|---|
csr_matrix | ndarray
|
The vertex–edge incidence matrix |
Notes
- If
values=False, the returned matrix is binarized before returning. - Use
sparse=Truefor large graphs to avoid memory blowups. - This is the canonical low-level structure that most algorithms (e.g., spectral clustering, Laplacian construction, hypergraph analytics) rely on.
__hash__()
Return a stable hash representing the current graph structure and metadata.
Returns:
| Type | Description |
|---|---|
int
|
A hash value that uniquely (within high probability) identifies the graph based on its topology and attributes. |
Behavior
- Includes the set of vertices, edges, and directedness in the hash.
- Includes graph-level attributes (if any) to capture metadata changes.
- Does not depend on memory addresses or internal object IDs, so the same graph serialized/deserialized or reconstructed with identical structure will produce the same hash.
Notes
- This method enables
AnnNetobjects to be used in hash-based containers (likesetordictkeys). - If the graph is mutated after hashing (e.g., vertices or edges are added or removed), the hash will no longer reflect the new state.
- The method uses a deterministic representation: sorted vertex/edge sets ensure that ordering does not affect the hash.
Views
annnet.core._Views.GraphView
Lazy view into a graph with deferred operations.
Provides filtered access to graph components without copying the underlying data. Views can be materialized into concrete subgraphs when needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
Parent graph instance |
required |
vertices
|
list[str] | set[str] | callable | None
|
vertex IDs to include, or predicate function |
None
|
edges
|
list[str] | set[str] | callable | None
|
Edge IDs to include, or predicate function |
None
|
slices
|
str | list[str] | None
|
slice ID(s) to include |
None
|
predicate
|
callable | None
|
Additional filter: predicate(vertex_id) -> bool |
None
|
Attributes
_graph = graph
instance-attribute
_vertices_filter = vertices
instance-attribute
_edges_filter = edges
instance-attribute
_predicate = predicate
instance-attribute
_slices = None
instance-attribute
_vertex_ids_cache = None
instance-attribute
_edge_ids_cache = None
instance-attribute
_computed = False
instance-attribute
obs
property
Return the filtered vertex attribute table for this view.
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.vertex_attributes and filters by the view's vertex IDs.
var
property
Return the filtered edge attribute table for this view.
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.edge_attributes and filters by the view's edge IDs.
X
property
Return the filtered incidence matrix subview.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
vertex_ids
property
Get filtered vertex IDs (cached).
Returns:
| Type | Description |
|---|---|
set[str] | None
|
None means no vertex filter (full graph). |
edge_ids
property
Get filtered edge IDs (cached).
Returns:
| Type | Description |
|---|---|
set[str] | None
|
None means no edge filter (full graph). |
vertex_count
property
Return the number of vertices in this view.
Returns:
| Type | Description |
|---|---|
int
|
|
edge_count
property
Return the number of edges in this view.
Returns:
| Type | Description |
|---|---|
int
|
|
Functions
__init__(graph, vertices=None, edges=None, slices=None, predicate=None)
_compute_ids()
Compute and cache filtered vertex and edge IDs.
edges_df(**kwargs)
Return an edge DataFrame view filtered to this view's edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Passed through to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.edges_view() and then filters by the view's edge IDs.
vertices_df(**kwargs)
Return a vertex DataFrame view filtered to this view's vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Passed through to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.vertices_view() and then filters by the view's vertex IDs.
materialize(copy_attributes=True)
Create a concrete subgraph from this view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy_attributes
|
bool
|
If True, copy vertex/edge attributes into the new graph. |
True
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
Materialized subgraph. |
Notes
Uses AnnNet.add_vertex(), add_edge(), add_hyperedge(), and get_*_attrs().
subview(vertices=None, edges=None, slices=None, predicate=None)
Create a new GraphView by further restricting this view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | callable | None
|
Vertex IDs or predicate; intersects with current view if provided. |
None
|
edges
|
Iterable[str] | callable | None
|
Edge IDs or predicate; intersects with current view if provided. |
None
|
slices
|
Iterable[str] | None
|
Slice IDs to include. Defaults to current view's slices if None. |
None
|
predicate
|
callable | None
|
Additional vertex predicate applied in conjunction with existing filters. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
Notes
Predicates are combined with logical AND.
summary()
Return a human-readable summary of this view.
Returns:
| Type | Description |
|---|---|
str
|
|
__repr__()
__len__()
annnet.core._Views.ViewsClass
Functions
edges_view(slice=None, include_directed=True, include_weight=True, resolved_weight=True, copy=True)
Build a DataFrame view of edges with optional slice join.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice ID to join per-slice attributes. |
None
|
include_directed
|
bool
|
Include directedness column. |
True
|
include_weight
|
bool
|
Include global weight column. |
True
|
resolved_weight
|
bool
|
Include effective weight (slice override if present). |
True
|
copy
|
bool
|
Return a cloned DataFrame if True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Vectorized implementation avoids per-edge scans.
vertices_view(copy=True)
Read-only vertex attribute table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
Columns include |
slices_view(copy=True)
Read-only slice attribute table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
Columns include |
aspects_view(copy=True)
Return a view of Kivela aspects and their metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Columns include aspect, elem_layers, and any aspect attribute keys.
layers_view(copy=True)
Return a read-only table of multi-aspect layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Columns include layer_tuple, layer_id, aspect columns, layer attributes,
and prefixed elementary layer attributes.
Internal helpers
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
directed = directed
instance-attribute
_vertex_RESERVED = set(_vertex_RESERVED)
instance-attribute
_EDGE_RESERVED = set(_EDGE_RESERVED)
instance-attribute
_slice_RESERVED = set(_slice_RESERVED)
instance-attribute
entity_to_idx = {}
instance-attribute
idx_to_entity = {}
instance-attribute
entity_types = {}
instance-attribute
edge_to_idx = {}
instance-attribute
idx_to_edge = {}
instance-attribute
edge_definitions = {}
instance-attribute
edge_weights = {}
instance-attribute
edge_directed = {}
instance-attribute
edge_direction_policy = {}
instance-attribute
_vertex_key_fields = None
instance-attribute
_vertex_key_index = {}
instance-attribute
_num_entities = 0
instance-attribute
_num_edges = 0
instance-attribute
_annotations_backend = annotations_backend
instance-attribute
hyperedge_definitions = {}
instance-attribute
graph_attributes = {}
instance-attribute
_next_edge_id = 0
instance-attribute
_slices = {}
instance-attribute
_default_slice = 'default'
instance-attribute
slice_edge_weights = defaultdict(dict)
instance-attribute
_current_slice = self._default_slice
instance-attribute
_matrix = sp.dok_matrix((n, e), dtype=(np.float32))
instance-attribute
_grow_rows_to = _grow_rows_to
instance-attribute
_grow_cols_to = _grow_cols_to
instance-attribute
_history_enabled = True
instance-attribute
_history = []
instance-attribute
_version = 0
instance-attribute
_history_clock0 = time.perf_counter_ns()
instance-attribute
_snapshots = []
instance-attribute
aspects = []
instance-attribute
elem_layers = {}
instance-attribute
_all_layers = ()
instance-attribute
_V = set()
instance-attribute
_VM = set()
instance-attribute
vertex_aligned = False
instance-attribute
_nl_to_row = {}
instance-attribute
_row_to_nl = []
instance-attribute
_legacy_single_aspect_enabled = True
instance-attribute
edge_kind = {}
instance-attribute
edge_layers = {}
instance-attribute
_aspect_attrs = {}
instance-attribute
_layer_attrs = {}
instance-attribute
_vertex_layer_attrs = {}
instance-attribute
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
__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.
_init_annotation_tables(annotations)
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).
_register_edge_as_entity(edge_id)
Make an existing edge connectable as an endpoint.
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. |
_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.
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. |
_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
|
|
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. |
_resolve_snapshot(ref)
Resolve snapshot reference (label, dict, or AnnNet).
_current_snapshot()
Create snapshot of current state (uses AnnNet attributes).
list_snapshots()
List all snapshots.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Snapshot metadata. |
Namespace for index operations. Provides clean API over existing dicts.
Attributes
_G = graph
instance-attribute
Functions
__init__(graph)
entity_to_row(entity_id)
Map an entity ID to its matrix row index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Row index for the entity. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the entity is not found. |
row_to_entity(row)
Map a matrix row index to its entity ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
int
|
Row index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Entity identifier. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the row index is not found. |
entities_to_rows(entity_ids)
Batch convert entity IDs to row indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_ids
|
Iterable[str]
|
Entity identifiers. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
|
rows_to_entities(rows)
Batch convert row indices to entity IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
Iterable[int]
|
Row indices. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
|
edge_to_col(edge_id)
Map an edge ID to its matrix column index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Column index for the edge. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the edge is not found. |
col_to_edge(col)
Map a matrix column index to its edge ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
int
|
Column index. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Edge identifier. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the column index is not found. |
edges_to_cols(edge_ids)
Batch convert edge IDs to column indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_ids
|
Iterable[str]
|
Edge identifiers. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
|
cols_to_edges(cols)
Batch convert column indices to edge IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
Iterable[int]
|
Column indices. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
|
entity_type(entity_id)
Get the entity type for an ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the entity is not found. |
is_vertex(entity_id)
Check whether an entity ID refers to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
is_edge_entity(entity_id)
Check whether an entity ID refers to an edge-entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
has_entity(entity_id)
Check if an ID exists as any entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
Entity identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
has_vertex(vertex_id)
Check if an ID exists and is a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
has_edge_id(edge_id)
Check if an edge ID exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
edge_count()
Return the number of edges in the graph.
Returns:
| Type | Description |
|---|---|
int
|
|
entity_count()
Return the number of entities (vertices + edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
|
vertex_count()
Return the number of true vertices (excludes edge-entities).
Returns:
| Type | Description |
|---|---|
int
|
|
stats()
Return index statistics for entities and edges.
Returns:
| Type | Description |
|---|---|
dict
|
|
Functions
_get_next_edge_id()
INTERNAL: Generate a unique edge ID for parallel edges.
Returns:
| Type | Description |
|---|---|
str
|
Fresh |
_ensure_vertex_table()
INTERNAL: Ensure the vertex attribute table exists with a canonical schema.
Notes
- Creates an empty Polars DF [DataFrame] with a single
Utf8vertex_idcolumn if missing or malformed.
_ensure_vertex_row(vertex_id)
INTERNAL: Ensure a row for vertex_id exists in the vertex attribute DF.
Notes
- Appends a new row with
vertex_idandNonefor other columns if absent. - Preserves existing schema and columns.
_vertex_key_enabled()
_build_key_from_attrs(attrs)
Return tuple of field values in declared order, or None if any missing.
_current_key_of_vertex(vertex_id)
Read the current key tuple of a vertex from vertex_attributes (None if incomplete).
_gen_vertex_id_from_key(key_tuple)
Deterministic, human-readable vertex_id from a composite key.
Functions
set_graph_attribute(key, value)
Set a graph-level attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute name. |
required |
value
|
Any
|
Attribute value. |
required |
get_graph_attribute(key, default=None)
Get a graph-level attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if the attribute is missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
set_vertex_attrs(vertex_id, **attrs)
Upsert pure vertex attributes (non-structural) into the vertex table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored. |
{}
|
set_vertex_attrs_bulk(updates)
Upsert vertex attributes in bulk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
updates
|
dict[str, dict] | Iterable[tuple[str, dict]]
|
Mapping or iterable of |
required |
get_attr_vertex(vertex_id, key, default=None)
Get a single vertex attribute (scalar) or default if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
get_vertex_attribute(vertex_id, attribute)
(Legacy alias) Get a single vertex attribute from the Polars DF [DataFrame].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex_id
|
str
|
Vertex identifier. |
required |
attribute
|
str or Enum
|
Column name or enum with |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
Scalar value if present, else None. |
See Also
get_attr_vertex
set_edge_attrs(edge_id, **attrs)
Upsert pure edge attributes (non-structural) into the edge DF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored. |
{}
|
set_edge_attrs_bulk(updates)
Upsert edge attributes in bulk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
updates
|
dict[str, dict] | Iterable[tuple[str, dict]]
|
Mapping or iterable of |
required |
get_attr_edge(edge_id, key, default=None)
Get a single edge attribute (scalar) or default if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
get_edge_attribute(edge_id, attribute)
(Legacy alias) Get a single edge attribute from the Polars DF [DataFrame].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
attribute
|
str or Enum
|
Column name or enum with |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
Scalar value if present, else None. |
See Also
get_attr_edge
set_slice_attrs(slice_id, **attrs)
Upsert pure slice attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored. |
{}
|
get_slice_attr(slice_id, key, default=None)
Get a single slice attribute (scalar) or default if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
set_edge_slice_attrs(slice_id, edge_id, **attrs)
Upsert per-slice attributes for a specific edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_id
|
str
|
Edge identifier. |
required |
**attrs
|
Attribute key/value pairs. Structural keys are ignored except |
{}
|
get_edge_slice_attr(slice_id, edge_id, key, default=None)
Get a per-slice attribute for an edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_id
|
str
|
Edge identifier. |
required |
key
|
str
|
Attribute name. |
required |
default
|
Any
|
Value to return if missing. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
set_slice_edge_weight(slice_id, edge_id, weight)
Set a legacy per-slice weight override for an edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_id
|
str
|
Edge identifier. |
required |
weight
|
float
|
Weight override. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice or edge does not exist. |
See Also
get_effective_edge_weight
get_effective_edge_weight(edge_id, slice=None)
Resolve the effective weight for an edge, optionally within a slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_id
|
str
|
Edge identifier. |
required |
slice
|
str
|
If provided, return the slice override if present; otherwise global weight. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Effective weight. |
audit_attributes()
Audit attribute tables for extra/missing rows and invalid edge-slice pairs.
Returns:
| Type | Description |
|---|---|
dict
|
Summary with keys:
- |
_dtype_for_value(v, *, prefer='polars')
INTERNAL: Infer an appropriate dtype class for value v.
- If Polars is available and prefer='polars', returns Polars dtype objects.
- Otherwise returns Narwhals dtype classes.
_is_null_dtype(dtype)
Check if a dtype represents a null/unknown type.
_ensure_attr_columns(df, attrs)
Create/align attribute columns and dtypes to accept attrs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoDataFrame
|
Existing attribute table (any supported backend). |
required |
attrs
|
dict
|
Incoming key/value pairs to upsert. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Narwhals DataFrame with columns added/cast so inserts/updates work. |
Notes
- New columns are created with the inferred dtype.
- If a column is Unknown (null-ish) and the incoming value is not, it is cast to the inferred dtype.
- If dtypes conflict, both sides upcast to String to avoid schema errors.
_sanitize_value_for_nw(v)
_is_binary_type(dt)
INTERNAL: Robustly identify binary types across backends.
_safe_nw_cast(column_expr, target_dtype)
INTERNAL: Attempt cast; fallback to String on engine rejection.
_upsert_row(df, idx, attrs)
_upsert_rows_bulk(df, updates)
_variables_watched_by_vertices()
_incident_flexible_edges(v)
_apply_flexible_direction(edge_id)
get_edge_attrs(edge)
Return the full attribute dict for a single edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge
|
int | str
|
Edge index or edge ID. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Attribute dictionary for that edge. Empty if not found. |
get_vertex_attrs(vertex)
Return the full attribute dict for a single vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertex
|
str
|
Vertex ID. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Attribute dictionary for that vertex. Empty if not found. |
get_attr_edges(indexes=None)
Retrieve edge attributes as a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indexes
|
Iterable[int] | None
|
Edge indices to retrieve. If None, returns all edges. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, dict]
|
Mapping of |
get_attr_vertices(vertices=None)
Retrieve vertex (vertex) attributes as a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | None
|
Vertex IDs to retrieve. If None, returns all vertices. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, dict]
|
Mapping of |
get_attr_from_edges(key, default=None)
Extract a specific attribute column for all edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute column name to extract. |
required |
default
|
Any
|
Value to use if the column or value is missing. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Mapping of |
get_edges_by_attr(key, value)
Retrieve all edges where a given attribute equals a specific value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Attribute column name to filter on. |
required |
value
|
Any
|
Value to match. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs where the attribute equals |
get_graph_attributes()
Return a shallow copy of the graph-level attributes dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Shallow copy of global graph metadata. |
Notes
Returned value is a shallow copy to prevent external mutation.
set_edge_slice_attrs_bulk(slice_id, items)
Upsert edge-slice attributes for a single slice in bulk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
items
|
Iterable[tuple[str, dict]] | dict[str, dict]
|
Iterable or mapping of |
required |
Functions
add_vertices_bulk(vertices, slice=None)
Bulk add vertices with a Polars fast path when available.
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
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
Falls back to Narwhals-based logic when Polars is unavailable.
add_vertices_bulk_nw(vertices, slice=None)
Bulk add vertices using Narwhals-compatible operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | Iterable[tuple[str, dict]] | Iterable[dict]
|
Vertices to add. |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This path is slower than the Polars fast path but preserves behavior.
add_edges_bulk(edges, *, slice=None, default_weight=1.0, default_edge_type='regular', default_propagate='none', default_slice_weight=None, default_edge_directed=None)
Bulk add or update binary edges (and vertex-edge edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
Iterable
|
Each item can be:
- |
required |
slice
|
str
|
Default slice to place edges into. |
None
|
default_weight
|
float
|
Default weight for edges missing an explicit weight. |
1.0
|
default_edge_type
|
str
|
Default edge type when not provided. |
'regular'
|
default_propagate
|
(none, shared, all)
|
Default slice propagation mode. |
'none'
|
default_slice_weight
|
float
|
Default per-slice weight override. |
None
|
default_edge_directed
|
bool
|
Default per-edge directedness override. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Edge IDs for created/updated edges. |
Notes
Behavior mirrors add_edge() but grows the matrix once to reduce overhead.
add_hyperedges_bulk(hyperedges, *, slice=None, default_weight=1.0, default_edge_directed=None)
Bulk add or update hyperedges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedges
|
Iterable[dict]
|
Each item can be:
- |
required |
slice
|
str
|
Default slice for hyperedges missing an explicit slice. |
None
|
default_weight
|
float
|
Default weight for hyperedges missing an explicit weight. |
1.0
|
default_edge_directed
|
bool
|
Default directedness override. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Hyperedge IDs for created/updated hyperedges. |
Notes
Behavior mirrors add_hyperedge() but grows the matrix once to reduce overhead.
add_edges_to_slice_bulk(slice_id, edge_ids)
Add many edges to a slice and attach all incident vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
edge_ids
|
Iterable[str]
|
Edge identifiers to add. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
No weights are changed in this operation.
add_edge_entities_bulk(items, slice=None)
Bulk add edge-entities (vertex-edge hybrids).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable
|
Accepts:
- iterable of string IDs
- iterable of |
required |
slice
|
str
|
Target slice. Defaults to the active slice. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
Attribute inserts are batched for efficiency.
set_vertex_key(*fields)
Declare composite key fields and rebuild the uniqueness index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*fields
|
str
|
Ordered field names used to build a composite key. |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If duplicates exist among already-populated vertices. |
Notes
Vertices missing some key fields are skipped during indexing.
remove_edges(edge_ids)
Remove many edges in one pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_ids
|
Iterable[str]
|
Edge identifiers to remove. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This is faster than calling remove_edge in a loop.
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 |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This is faster than calling remove_vertex in a loop.
_remove_edges_bulk(edge_ids)
_remove_vertices_bulk(vertex_ids)
Functions
_utcnow_iso()
_jsonify(x)
_log_event(op, **fields)
_log_mutation(name=None)
_install_history_hooks()
history(as_df=False)
Return the append-only mutation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_df
|
bool
|
If True, return a DataFrame; otherwise return a list of dicts. |
False
|
Returns:
| Type | Description |
|---|---|
list[dict] | DataFrame
|
Event records including |
Notes
Ordering is guaranteed by version and mono_ns. The log is in-memory
until exported.
export_history(path)
Write the mutation history to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Output path. Supported extensions: |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of events written. Returns 0 if the history is empty. |
Raises:
| Type | Description |
|---|---|
OSError
|
If the file cannot be written. |
Notes
Unknown extensions default to Parquet by appending .parquet.
enable_history(flag=True)
Enable or disable in-memory mutation logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flag
|
bool
|
When True, start/continue logging; when False, pause logging. |
True
|
Returns:
| Type | Description |
|---|---|
None
|
|
clear_history()
Clear the in-memory mutation log.
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
This does not delete any files previously exported.
mark(label)
Insert a manual marker into the mutation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Human-readable tag for the marker event. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Notes
The event is recorded with op='mark' alongside standard fields
(version, ts_utc, mono_ns). Logging must be enabled for the
marker to be recorded.
Represents the difference between two graph states.
Attributes:
| Name | Type | Description |
|---|---|---|
vertices_added |
set
|
Vertices in b but not in a |
vertices_removed |
set
|
Vertices in a but not in b |
edges_added |
set
|
Edges in b but not in a |
edges_removed |
set
|
Edges in a but not in b |
slices_added |
set
|
slices in b but not in a |
slices_removed |
set
|
slices in a but not in b |
Attributes
snapshot_a = snapshot_a
instance-attribute
snapshot_b = snapshot_b
instance-attribute
vertices_added = snapshot_b['vertex_ids'] - snapshot_a['vertex_ids']
instance-attribute
vertices_removed = snapshot_a['vertex_ids'] - snapshot_b['vertex_ids']
instance-attribute
edges_added = snapshot_b['edge_ids'] - snapshot_a['edge_ids']
instance-attribute
edges_removed = snapshot_a['edge_ids'] - snapshot_b['edge_ids']
instance-attribute
slices_added = snapshot_b['slice_ids'] - snapshot_a['slice_ids']
instance-attribute
slices_removed = snapshot_a['slice_ids'] - snapshot_b['slice_ids']
instance-attribute
Functions
__init__(snapshot_a, snapshot_b)
summary()
Return a human-readable summary of differences.
Returns:
| Type | Description |
|---|---|
str
|
Summary text describing added/removed vertices, edges, and slices. |
is_empty()
Check whether the diff contains no changes.
Returns:
| Type | Description |
|---|---|
bool
|
|
__repr__()
to_dict()
Convert the diff to a serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
|
Cache manager for materialized views (CSR/CSC).
Attributes
_G = graph
instance-attribute
_csr = None
instance-attribute
_csc = None
instance-attribute
_adjacency = None
instance-attribute
_csr_version = None
instance-attribute
_csc_version = None
instance-attribute
_adjacency_version = None
instance-attribute
csr
property
Return the CSR (Compressed Sparse Row) matrix.
Returns:
| Type | Description |
|---|---|
csr_matrix
|
|
Notes
Built and cached on first access.
csc
property
Return the CSC (Compressed Sparse Column) matrix.
Returns:
| Type | Description |
|---|---|
csc_matrix
|
|
Notes
Built and cached on first access.
adjacency
property
Return the adjacency matrix computed from incidence.
Returns:
| Type | Description |
|---|---|
spmatrix
|
|
Notes
For incidence matrix B, adjacency is computed as A = B @ B.T.
Functions
__init__(graph)
has_csr()
Check whether a valid CSR cache exists.
Returns:
| Type | Description |
|---|---|
bool
|
|
has_csc()
Check whether a valid CSC cache exists.
Returns:
| Type | Description |
|---|---|
bool
|
|
has_adjacency()
Check whether a valid adjacency cache exists.
Returns:
| Type | Description |
|---|---|
bool
|
|
get_csr()
Return the cached CSR matrix.
Returns:
| Type | Description |
|---|---|
csr_matrix
|
|
get_csc()
Return the cached CSC matrix.
Returns:
| Type | Description |
|---|---|
csc_matrix
|
|
get_adjacency()
Return the cached adjacency matrix.
Returns:
| Type | Description |
|---|---|
spmatrix
|
|
invalidate(formats=None)
Invalidate cached formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formats
|
list[str]
|
Formats to invalidate ( |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
build(formats=None)
Pre-build specified formats (eager caching).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formats
|
list[str]
|
Formats to build ( |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
clear()
Clear all caches.
Returns:
| Type | Description |
|---|---|
None
|
|
info()
Get cache status and memory usage.
Returns:
| Type | Description |
|---|---|
dict
|
Status and size information for each cached format. |
Functions
edge_subgraph(edges)
Create a subgraph containing only a specified subset of edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
Iterable[str] | Iterable[int]
|
Edge identifiers or edge indices to retain. |
required |
Returns:
| Type | Description |
|---|---|
AnnNet
|
Subgraph containing selected edges and their incident vertices. |
Notes
Hyperedges are supported and retain all member vertices.
subgraph(vertices)
Create a vertex-induced subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str]
|
Vertex identifiers to retain. |
required |
Returns:
| Type | Description |
|---|---|
AnnNet
|
Subgraph containing only the specified vertices and their internal edges. |
Notes
For hyperedges, all member vertices must be included to retain the edge.
extract_subgraph(vertices=None, edges=None)
Create a subgraph based on vertex and/or edge filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | None
|
Vertex IDs to include. If None, no vertex filtering is applied. |
None
|
edges
|
Iterable[str] | Iterable[int] | None
|
Edge IDs or indices to include. If None, no edge filtering is applied. |
None
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
Filtered subgraph. |
Notes
This is a convenience method that delegates to subgraph() and
edge_subgraph() internally.
reverse()
Return a new graph with all directed edges reversed.
Returns:
| Type | Description |
|---|---|
AnnNet
|
A new |
Behavior
- Binary edges: direction is flipped by swapping source and target.
- Directed hyperedges:
headandtailsets are swapped. - Undirected edges/hyperedges: unaffected.
- Edge attributes and metadata are preserved.
Notes
- This operation does not modify the original graph.
- If the graph is undirected (
self.directed == False), the result is identical to the original. - For mixed graphs (directed + undirected edges), only the directed ones are reversed.
subgraph_from_slice(slice_id, *, resolve_slice_weights=True)
Create a subgraph induced by a single slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_id
|
str
|
Slice identifier. |
required |
resolve_slice_weights
|
bool
|
If True, use per-slice edge weights when available. |
True
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
Subgraph containing the slice vertices and edges. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the slice does not exist. |
_row_attrs(df, key_col, key)
INTERNAL: return a dict of attributes for the row in df where key_col == key,
excluding the key column itself. If not found or df empty, return {}.
Caches per (id(df), key_col) for speed; cache auto-refreshes when the df object changes.
copy(history=False)
Deep copy of the entire AnnNet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history
|
bool
|
If True, copy the mutation history and snapshot timeline. If False, the new graph starts with a clean history. |
False
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
A new graph with full structural and attribute fidelity. |
Notes
O(N) Python, O(nnz) matrix; this path is optimized for speed.
memory_usage()
Approximate total memory usage in bytes.
Returns:
| Type | Description |
|---|---|
int
|
Estimated bytes for the incidence matrix, dictionaries, and attribute DFs. |
get_vertex_incidence_matrix_as_lists(values=False)
Materialize the vertex–edge incidence structure as Python lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
(bool, optional(default=False))
|
|
False
|
Returns:
| Type | Description |
|---|---|
dict[str, list]
|
A mapping from |
Notes
- Internally uses the sparse incidence matrix
self._matrix, which is stored as a SciPy CSR (compressed sparse row) matrix or similar. - The incidence matrix
Mis defined as:- Rows: vertices
- Columns: edges
- Entry
M[i, j]non-zero ⇨ vertexiis incident to edgej.
- This is a convenient method when you want a native-Python structure for downstream use (e.g., exporting, iterating, or visualization).
vertex_incidence_matrix(values=False, sparse=False)
Return the vertex–edge incidence matrix in sparse or dense form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
(bool, optional(default=False))
|
If |
False
|
sparse
|
(bool, optional(default=False))
|
|
False
|
Returns:
| Type | Description |
|---|---|
csr_matrix | ndarray
|
The vertex–edge incidence matrix |
Notes
- If
values=False, the returned matrix is binarized before returning. - Use
sparse=Truefor large graphs to avoid memory blowups. - This is the canonical low-level structure that most algorithms (e.g., spectral clustering, Laplacian construction, hypergraph analytics) rely on.
__hash__()
Return a stable hash representing the current graph structure and metadata.
Returns:
| Type | Description |
|---|---|
int
|
A hash value that uniquely (within high probability) identifies the graph based on its topology and attributes. |
Behavior
- Includes the set of vertices, edges, and directedness in the hash.
- Includes graph-level attributes (if any) to capture metadata changes.
- Does not depend on memory addresses or internal object IDs, so the same graph serialized/deserialized or reconstructed with identical structure will produce the same hash.
Notes
- This method enables
AnnNetobjects to be used in hash-based containers (likesetordictkeys). - If the graph is mutated after hashing (e.g., vertices or edges are added or removed), the hash will no longer reflect the new state.
- The method uses a deterministic representation: sorted vertex/edge sets ensure that ordering does not affect the hash.
Lazy view into a graph with deferred operations.
Provides filtered access to graph components without copying the underlying data. Views can be materialized into concrete subgraphs when needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AnnNet
|
Parent graph instance |
required |
vertices
|
list[str] | set[str] | callable | None
|
vertex IDs to include, or predicate function |
None
|
edges
|
list[str] | set[str] | callable | None
|
Edge IDs to include, or predicate function |
None
|
slices
|
str | list[str] | None
|
slice ID(s) to include |
None
|
predicate
|
callable | None
|
Additional filter: predicate(vertex_id) -> bool |
None
|
Attributes
_graph = graph
instance-attribute
_vertices_filter = vertices
instance-attribute
_edges_filter = edges
instance-attribute
_predicate = predicate
instance-attribute
_slices = None
instance-attribute
_vertex_ids_cache = None
instance-attribute
_edge_ids_cache = None
instance-attribute
_computed = False
instance-attribute
obs
property
Return the filtered vertex attribute table for this view.
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.vertex_attributes and filters by the view's vertex IDs.
var
property
Return the filtered edge attribute table for this view.
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.edge_attributes and filters by the view's edge IDs.
X
property
Return the filtered incidence matrix subview.
Returns:
| Type | Description |
|---|---|
dok_matrix
|
|
vertex_ids
property
Get filtered vertex IDs (cached).
Returns:
| Type | Description |
|---|---|
set[str] | None
|
None means no vertex filter (full graph). |
edge_ids
property
Get filtered edge IDs (cached).
Returns:
| Type | Description |
|---|---|
set[str] | None
|
None means no edge filter (full graph). |
vertex_count
property
Return the number of vertices in this view.
Returns:
| Type | Description |
|---|---|
int
|
|
edge_count
property
Return the number of edges in this view.
Returns:
| Type | Description |
|---|---|
int
|
|
Functions
__init__(graph, vertices=None, edges=None, slices=None, predicate=None)
_compute_ids()
Compute and cache filtered vertex and edge IDs.
edges_df(**kwargs)
Return an edge DataFrame view filtered to this view's edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Passed through to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.edges_view() and then filters by the view's edge IDs.
vertices_df(**kwargs)
Return a vertex DataFrame view filtered to this view's vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Passed through to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Uses AnnNet.vertices_view() and then filters by the view's vertex IDs.
materialize(copy_attributes=True)
Create a concrete subgraph from this view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy_attributes
|
bool
|
If True, copy vertex/edge attributes into the new graph. |
True
|
Returns:
| Type | Description |
|---|---|
AnnNet
|
Materialized subgraph. |
Notes
Uses AnnNet.add_vertex(), add_edge(), add_hyperedge(), and get_*_attrs().
subview(vertices=None, edges=None, slices=None, predicate=None)
Create a new GraphView by further restricting this view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vertices
|
Iterable[str] | callable | None
|
Vertex IDs or predicate; intersects with current view if provided. |
None
|
edges
|
Iterable[str] | callable | None
|
Edge IDs or predicate; intersects with current view if provided. |
None
|
slices
|
Iterable[str] | None
|
Slice IDs to include. Defaults to current view's slices if None. |
None
|
predicate
|
callable | None
|
Additional vertex predicate applied in conjunction with existing filters. |
None
|
Returns:
| Type | Description |
|---|---|
GraphView
|
|
Notes
Predicates are combined with logical AND.
summary()
Return a human-readable summary of this view.
Returns:
| Type | Description |
|---|---|
str
|
|
__repr__()
__len__()
Functions
edges_view(slice=None, include_directed=True, include_weight=True, resolved_weight=True, copy=True)
Build a DataFrame view of edges with optional slice join.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice
|
str
|
Slice ID to join per-slice attributes. |
None
|
include_directed
|
bool
|
Include directedness column. |
True
|
include_weight
|
bool
|
Include global weight column. |
True
|
resolved_weight
|
bool
|
Include effective weight (slice override if present). |
True
|
copy
|
bool
|
Return a cloned DataFrame if True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Vectorized implementation avoids per-edge scans.
vertices_view(copy=True)
Read-only vertex attribute table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
Columns include |
slices_view(copy=True)
Read-only slice attribute table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
Columns include |
aspects_view(copy=True)
Return a view of Kivela aspects and their metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Columns include aspect, elem_layers, and any aspect attribute keys.
layers_view(copy=True)
Return a read-only table of multi-aspect layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
copy
|
bool
|
Return a cloned DataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame - like
|
|
Notes
Columns include layer_tuple, layer_id, aspect columns, layer attributes,
and prefixed elementary layer attributes.