API reference¶
Generated from the type stubs (python/ironweaver/__init__.pyi), which document every public class and function.
Vertex ¶
A directed property graph backed by ironweaver_core::Graph (pure Rust).
meta
instance-attribute
¶
meta: dict[str, Any]
Arbitrary graph-level metadata. Traversal methods may populate meta["nodelist"].
nodes
property
¶
nodes: dict[str, Node]
A new dict mapping node ID → Node for all nodes in the graph.
clone ¶
clone() -> Vertex
Deep-copy the graph, attributes and metadata; callback lists start empty.
Preserves node IDs, labels, edge IDs/types, indexes and shuffle seed. Built-in containers/scalars copy in Rust; other values use Python's copy.deepcopy with the same memo (including custom hooks).
set_shuffle_seed ¶
set_shuffle_seed(seed: int | None = None) -> None
Set the testing seed; None restores default order. Not serialized.
keys ¶
keys() -> list[str]
Return all node IDs (graph order: insertion order until nodes are removed).
add_node ¶
add_node(id: str, attr: dict[str, Any] | None = ..., labels: list[str] | None = ...) -> Node
Add a node and return it. Raises ValueError if id already exists.
An attr["labels"] list of str becomes the node's labels.
add_edge ¶
add_edge(from_id: str, to_id: str, attr: dict[str, Any] | None = ..., type: str | None = ...) -> Edge
Add a directed edge and return it. Raises ValueError if either node is missing.
An attr["type"] str becomes the edge's type. The edge gets a new
persistent id.
add_nodes ¶
add_nodes(nodes: Iterable[str | tuple[str, dict[str, Any]] | list[Any]], *, labels: list[str] | None = ..., attrs: dict[str, Sequence[Any]] | None = ...) -> int
Add many nodes in one call; each item is an id or (id, attrs).
labels go on every node. attrs gives attributes as columns,
{name: [one value per node]} (None: not set; a "labels"
column sets labels). Every item is checked first: on an error nothing
is added. Returns the number of nodes added.
add_edges ¶
add_edges(edges: Iterable[tuple[str, str] | tuple[str, str, dict[str, Any]] | list[Any]], *, type: str | None = ..., attrs: dict[str, Sequence[Any]] | None = ...) -> int
Add many edges in one call; each item is (from_id, to_id) or
(from_id, to_id, attrs).
type applies to every edge. attrs gives attributes as columns,
{name: [one value per edge]} (None: not set; a "type" column
sets types) — the fastest way to load weights. Every item is checked
first: on an error nothing is added. Returns the number of edges added.
get_edge ¶
get_edge(id: int) -> Edge
The edge with this persistent id. Raises KeyError if there is none.
nodes_with_label ¶
nodes_with_label(label: str) -> list[Node]
Nodes carrying label, in graph order (label index).
labels ¶
labels() -> dict[str, int]
Every label at least one node carries, with its number of nodes, in the order the labels were first used (label index).
edge_types ¶
edge_types() -> dict[str | None, int]
Every edge type at least one edge has, with its number of edges:
untyped edges first (key None, if there are any), then the types
in the order they were first used. The counts are kept as edges
change, so this costs O(labels + types), not a scan of the edges.
create_index ¶
create_index(name: str) -> bool
Index node attribute name for fast :meth:find / :meth:find_range.
filter(where=...) and :meth:match use indexes automatically.
The index follows every change made through the graph's methods, and
is saved with the graph (its definition; loading rebuilds it). Only
scalar values are indexed (numbers, strings, bools, bytes, dates,
datetimes). Returns False if the index already existed.
index_stats ¶
index_stats(name: str) -> dict[str, int] | None
Size of the index on name, or None if name isn't indexed. O(1).
entries is the number of indexed nodes (those with a scalar value),
distinct_keys the number of distinct values (1 and 1.0 are one),
memory_bytes the approximate bytes the index uses (part of
:meth:memory_usage), and dirty the number of nodes whose entries
may be stale; the counts are exact when it is 0, as after changes
made through the graph's methods.
find ¶
find(name: str, value: Any) -> list[Node]
Nodes whose attribute name equals value (1 == 1.0), in graph order.
Uses the index on name if there is one, else scans every node.
find_range ¶
find_range(name: str, low: Any = ..., high: Any = ..., *, inclusive: Literal['both', 'left', 'right', 'neither'] = ...) -> list[Node]
Nodes whose attribute name lies between low and high, in graph order.
Either bound may be None (open). Bounds are numbers, strings, bools, bytes, dates or datetimes, of one kind; values of another kind are never in range. Uses the index on name if there is one.
match ¶
match(pattern: str, *, where: dict[str, Expr] | None = ..., ids: dict[str, str | list[str]] | None = ..., limit: int | None = ...) -> list[dict[str, Node | Edge | list[Edge]]]
Every occurrence of a Cypher-like pattern, e.g.
"(a:Person {name: 'Ann'})-[k:KNOWS*1..3]->(b)": one dict per match
from variable name to Node, Edge, or list of Edges (variable-length).
Each pattern edge binds a different edge; nodes may repeat.
where adds Expr conditions per variable, ids fixes node
variables, limit caps the matches. See docs/patterns.md.
remove_node ¶
remove_node(id: str) -> Node
Remove a node and every edge attached to it.
Returns a detached copy of the node (same id, attr and meta, no edges) in a new one-node Vertex; existing handles to the removed node raise RuntimeError when used. Raises KeyError if the node does not exist.
remove_edge ¶
remove_edge(from_id: str, to_id: str, attr: dict[str, Any] | None = ...) -> int
Remove edges from from_id to to_id and return how many were removed.
If attr is given, only edges whose attributes match every key/value
pair are removed, e.g. g.remove_edge("a", "b", {"type": "knows"}).
Raises ValueError if either node does not exist.
save_to_json ¶
save_to_json(file_path: str | None = ..., pretty: bool = ...) -> str | None
Serialize to JSON.
If file_path is given, writes to that path and returns None.
If file_path is None, returns the JSON string.
Output is compact by default; pass pretty=True for indented JSON.
Raises RuntimeError if a value cannot be serialized or the file
cannot be written.
to_binary ¶
to_binary() -> bytes
Return format-v2 binary bytes without file I/O; includes the checksum.
from_binary
staticmethod
¶
from_binary(data: bytes) -> Vertex
Load format-v2 binary bytes, validating the header and checksum.
save_to_binary_f16 ¶
save_to_binary_f16(file_path: str) -> None
Like save_to_binary but stores floats as f16 to reduce file size.
load_from_json
staticmethod
¶
load_from_json(source: str | dict[str, Any]) -> Vertex
Load from a file path, a raw JSON string, or a plain dict.
from_nodes
staticmethod
¶
from_nodes(nodes: dict[str, Node]) -> Vertex
A new Vertex with copies of the given nodes (keyed by the dict keys) and of the edges between them.
from_nodes_with_path
staticmethod
¶
from_nodes_with_path(nodes: dict[str, Node], nodelist: list[str]) -> Vertex
Like from_nodes but also stores nodelist in meta["nodelist"].
memory_usage ¶
memory_usage(*, deep: bool = ...) -> int
Approximate bytes used by the graph structure (nodes, edges, ids, adjacency, labels, indexes).
With deep, also the attribute / meta dicts and their values
(sys.getsizeof, containers recursively, shared objects once).
get_metadata ¶
get_metadata() -> dict[str, Any]
Return summary metadata about the graph.
Returned keys:
================== =================================================
node_count Number of nodes (int)
edge_count Number of edges (int)
average_degree Mean number of outgoing edges per node (float)
node_ids List of all node ID strings
================== =================================================
to_networkx ¶
to_networkx() -> Any
Convert to a networkx.DiGraph. Requires networkx to be installed.
shortest_path ¶
shortest_path(source: str, target: str, method: Literal['bfs', 'dijkstra', 'astar'] | None = ..., *, weight: str | None = ..., default_weight: float | None = ..., max_cost: float | None = ..., direction: Literal['out', 'in', 'both'] | None = ..., max_depth: int | None = ..., heuristic: Literal['euclidean', 'manhattan'] | None = ..., coords: str | list[str] | None = ..., distances: str | None = ...) -> Vertex
Shortest path with method "bfs", "dijkstra" or "astar"; see path_methods().
Equal-cost ties go by node order (insertion order), never edge order: walking back from the target, the earliest neighbour on a cheapest route.
path_methods
staticmethod
¶
path_methods() -> dict[str, str]
The available shortest_path methods as {name: description}.
project ¶
project(weight: str | None = ..., default_weight: float | None = ..., *, direction: Literal['out', 'in', 'both'] | None = ..., nodes: list[str] | None = ..., node_filter: dict[str, Any] | Callable[[NodeView], bool] | None = ..., edge_filter: dict[str, Any] | Callable[[EdgeView], bool] | None = ..., coords: str | list[str] | None = ...) -> Projection
Patched in ironweaver/init.py: callables receive NodeView / EdgeView.
shortest_paths ¶
shortest_paths(pairs: list[tuple[str, str]], method: Literal['bfs', 'dijkstra', 'astar'] | None = ..., *, weight: str | None = ..., default_weight: float | None = ..., max_cost: float | None = ..., direction: Literal['out', 'in', 'both'] | None = ..., coords: str | list[str] | None = ..., heuristic: Literal['euclidean', 'manhattan'] | None = ..., heuristic_scale: float | None = ...) -> list[dict[str, Any] | None]
Shortest paths for many (source, target) pairs, in parallel.
With stats=True, each found path includes "stats": {"settled": n}.
Counts are Dijkstra settled nodes, A* expansions (including reopens),
or BFS nodes reached; unreachable entries stay None.
The graph and its edge costs are copied into a projection once, then
all queries run on every core with the GIL released (use
:meth:project to reuse one for several batches). Returns one
entry per pair: {"nodelist": [...], "cost": ...} (cost is the number
of edges for "bfs"), or None if the target is unreachable. Methods
"bfs", "dijkstra" and "astar" (as in :meth:Projection.shortest_paths,
with node coordinates at coords, ["x", "y"] by default; every
node needs them). method=None picks "astar" if coords,
heuristic or heuristic_scale is given. Edge weights (and
coordinates) of the whole graph are validated when the projection is
built. For a single query use shortest_path.
Paths, ties between equal-cost paths included, are those
shortest_path returns (earliest node in insertion order walking
back from the target), for any number of threads. With
Vertex(shuffle_seed=...) the projection numbers nodes in the
shuffled order, which then decides ties.
distances ¶
distances(sources: list[str], targets: list[str] | None = ..., method: Literal['bfs', 'dijkstra'] | None = ..., *, weight: str | None = ..., default_weight: float | None = ..., max_cost: float | None = ..., direction: Literal['out', 'in', 'both'] | None = ...) -> dict[str, dict[str, float]]
{source: {node: cost}} for every node each source reaches within
max_cost (only targets, if given), computed in parallel like
shortest_paths. Methods "bfs" and "dijkstra": "astar" needs one
target per query.
shortest_path_bfs ¶
shortest_path_bfs(root_node_id: str, target_node_id: str, max_depth: int | None = ..., direction: Literal['out', 'in', 'both'] | None = ...) -> Vertex
Ordered path is in result.meta["nodelist"]. Raises ValueError if unreachable.
shortest_path_dijkstra ¶
shortest_path_dijkstra(root_node_id: str, target_node_id: str, weight: str | None = ..., default_weight: float | None = ..., max_cost: float | None = ..., direction: Literal['out', 'in', 'both'] | None = ...) -> Vertex
Path in result.meta["nodelist"], total cost in result.meta["cost"].
expand ¶
expand(source_vertex: Vertex, depth: int | None = ..., direction: Literal['out', 'in', 'both'] | None = ...) -> Vertex
Expand this subgraph by pulling neighbour nodes from source_vertex.
depth defaults to 1 (one hop).
By default only outgoing edges are followed; nodes that point
into the seed nodes are not included. Pass direction="in" to
follow incoming edges instead, or direction="both" for both.
Example::
seed = graph.filter(id="ckd")
expanded = seed.expand(graph, depth=1)
# expanded now contains ckd + all nodes ckd has outgoing edges to
filter ¶
filter(predicate: Callable[[NodeView], bool] | Expr | None = ..., *, ids: list[str] | None = ..., id: str | None = ..., where: Expr | None = ..., **kwargs: Any) -> Vertex
Patched at import time by ironweaver/init.py to accept a predicate callable.
prune ¶
prune() -> int
Kept for compatibility; always returns 0.
Edges always connect two nodes of their own graph (results of filter/traversals/from_nodes only copy the edges between their nodes), so there are never dangling edges to remove.
random_walks ¶
random_walks(start_node_id: str | None, max_length: int, num_attempts: int, min_length: int | None = ..., allow_revisit: bool | None = ..., include_edge_types: bool | None = ..., edge_type_field: str | None = ..., stratified: bool | None = ..., seed: int | None = ...) -> list[list[str]]
Perform random walks from start_node_id.
Parameters¶
start_node_id:
ID of the starting node. May be None only when stratified=True,
in which case each walk's start node is sampled across the whole
graph (favouring least-visited nodes).
max_length:
Maximum number of hops per walk.
num_attempts:
Number of walk attempts. Duplicate walks are removed automatically.
min_length:
Minimum walk length to include. Defaults to no minimum.
allow_revisit:
Allow visiting the same node twice. Defaults to False.
include_edge_types:
If True, each walk alternates between node IDs and edge-type strings,
e.g. ["alice", "knows", "bob"]. Defaults to False.
edge_type_field:
Attribute key used to read the edge type. Defaults to "type".
stratified:
If True, aim for equal node visit frequencies: every choice (the
start node when start_node_id is None, and each step) is weighted
by 1 / (1 + times_visited), steering walks towards the
least-visited nodes. Visit counts persist across all attempts of
one call. Defaults to False.
seed:
Seed for the random number generator. The same seed and arguments
always produce the same walks. Defaults to a random seed.
Walks run in native code without holding the GIL; non-stratified walks are spread over all CPU cores.
Returns a list of walks; each walk is a list of strings.
Example::
walks = graph.random_walks("node1", 5, 20)
walks = graph.random_walks("node1", 5, 20, include_edge_types=True)
walks = graph.random_walks(None, 5, 50, stratified=True)
walks = graph.random_walks("node1", 5, 20, seed=42) # reproducible
Node ¶
A graph node with a string ID, an attribute dict, and directed edge lists.
id
instance-attribute
¶
id: str
Unique node identifier (assigning renames the node; ValueError if taken).
attr
instance-attribute
¶
attr: dict[str, Any]
Node attributes (a copy), e.g. {"type": "Person", "age": 30}. Labels show up under "labels"; assigning a dict with a list of str "labels" sets them.
on_update_callbacks
property
¶
on_update_callbacks: list[Callable[[Vertex, Node, str, Any, Any | None], bool]]
The owning Vertex's on_node_update_callbacks (fired by attr_set).
traverse ¶
traverse(depth: int | None = ..., filter: dict[str, Any] | Callable[[EdgeView], bool] | None = ..., edge_filter: Callable[[EdgeView], bool] | None = ...) -> Vertex
DFS traversal. filter/edge_filter receive an EdgeView from the Python wrapper.
bfs ¶
bfs(depth: int | None = ..., filter: dict[str, Any] | Callable[[EdgeView], bool] | None = ..., edge_filter: Callable[[EdgeView], bool] | None = ...) -> Vertex
BFS traversal. filter/edge_filter receive an EdgeView from the Python wrapper.
bfs_search ¶
bfs_search(target_id: str, depth: int | None = ..., filter: dict[str, Any] | Callable[[EdgeView], bool] | None = ..., edge_filter: Callable[[EdgeView], bool] | None = ...) -> Node | None
BFS search for target_id. Returns the Node if found, None otherwise.
attr_set ¶
attr_set(key: str, value: Any) -> None
Set attr[key] = value and fire on_update_callbacks if the value changed.
attr_list_append ¶
attr_list_append(key: str, value: Any) -> None
Append value to the list stored at attr[key], creating it if missing.
paths ¶
paths(min_hops: int = ..., max_hops: int | None = ..., *, direction: Literal['out', 'in', 'both'] | None = ..., types: str | list[str] | None = ..., where: Expr | None = ..., uniqueness: Literal['trail', 'path', 'walk'] = ..., limit: int | None = ...) -> list[Path]
Every path from this node with min_hops..max_hops edges, depth first. uniqueness: "trail" (no edge twice; default), "path" (no node twice) or "walk" (needs max_hops). types / where restrict the edges followed; limit caps the number of paths.
Edge ¶
A directed, attributed edge between two nodes (a handle into its vertex).
id
property
¶
id: int
Persistent id: unique in its graph, never reused, kept by save/load
and derived graphs (Vertex.get_edge(id)).
attr
instance-attribute
¶
attr: dict[str, Any]
Edge attributes (a copy), e.g. {"since": 2020, "type": "knows"}. The type shows up under "type"; assigning a dict with a str "type" sets it.
on_update_callbacks
property
¶
on_update_callbacks: list[Callable[[Vertex, Edge, str, Any, Any | None], bool]]
The owning Vertex's on_edge_update_callbacks (fired by attr_set).
attr_set ¶
attr_set(key: str, value: Any) -> None
Set attr[key] = value and fire on_update_callbacks if the value changed.
Projection ¶
Compact read-only copy of a graph for analytics (see Vertex.project).
direction
property
¶
direction: Literal['out', 'in', 'both']
How edges were followed: "in" reversed them, "both" made them undirected.
from_arrays
staticmethod
¶
from_arrays(ids: Sequence[str], src: Buffer | Sequence[int], dst: Buffer | Sequence[int], weight: Buffer | Sequence[float] | None = ..., coords: Buffer | Sequence[Sequence[float]] | None = ..., *, direction: Literal['out', 'in', 'both'] | None = ...) -> Projection
Build a projection from arrays, without a :class:Vertex.
Node i has id ids[i]; edge k goes from ids[src[k]] to
ids[dst[k]] with weight weight[k] (unweighted if None).
Edges keep the order given (parallel edges in it), so the result is
the same as vertex.project(weight=..., direction=...) on a Vertex
with these nodes and edges added in this order; a caller can make
tie-breaking canonical by sorting the edges.
src / dst are 1-D numpy arrays of int64 or int32 (copied without a
Python call per item) or sequences of ints; weight a 1-D float64 /
float32 array or a sequence of numbers. coords (an (n, d) array or
n rows of d numbers) are node coordinates, for shortest_paths(...,
"astar"). direction:
"out" (default), "in" (reversed) or "both" (undirected).
Raises ValueError for duplicate ids, arrays of different lengths,
indices outside 0 .. len(ids) - 1, negative or NaN weights, and
coords that are not finite or not one row per node; TypeError for
arrays of the wrong type.
neighbors ¶
neighbors(id: str, direction: Literal['out', 'in'] | None = ...) -> list[str]
Ids one edge away, sorted by projection order; parallel edges repeat.
set_weights ¶
set_weights(edges: Buffer | Sequence[int], weights: Buffer | Sequence[float]) -> None
Change the weights of some edges in place: edge edges[i] gets
weights[i] (if an edge is listed twice, the last weight wins).
Edges are numbered in projected order: for :meth:from_arrays, the
order of the edge arrays (edge k is src[k] -> dst[k]); for
:meth:Vertex.project, the order in which the Vertex stores its
edges, among the projected ones (:meth:edge_index gives an edge's
number). One edge is one number whatever the direction: on a "both"
projection it is listed from both ends, and both entries change.
The structure stays the same. inf makes an edge impassable: every
search skips it (shortest paths and distances with any method, BFS
levels, k shortest paths, betweenness, closeness and harmonic
centrality, also unweighted; node2vec walks), the spanning tree
leaves it out, and PageRank, FastRP, Leiden and modularity count it
as weight 0. Algorithms that only look at the structure (components,
topological sort, cycles, degree, triangles, clustering, k-core,
label propagation, similarity, neighbors / degree) still see
it. A finite weight makes it passable again.
Afterwards every method returns what a projection built with the new
weights would. Each call costs time in proportion to the number of
edges changed, not to the size of the projection. edges and
weights are numpy arrays (int64 / int32, float64 / float32) or
sequences, as for :meth:from_arrays.
Raises ValueError (changing nothing) on an unweighted projection,
lists of different lengths, an index outside 0 .. edge_count() -
1, or a negative or NaN weight; RuntimeError if a query is running
on this projection in another thread meanwhile.
edge_index ¶
edge_index(edge: Edge) -> int
The number of edge (an :class:Edge of the Vertex this
projection was made from) in projected order, as :meth:set_weights
takes it.
Raises ValueError if the projection is not a weighted one made by
:meth:Vertex.project (only those keep their edges), if the edge
belongs to another Vertex, or if it was not projected (filtered out,
or added or removed since).
shortest_paths ¶
shortest_paths(pairs: Sequence[tuple[str, str]] | Sequence[tuple[int, int]] | Buffer, method: Literal['bfs', 'dijkstra', 'astar'] | None = ..., *, max_cost: float | None = ..., heuristic: Literal['euclidean', 'manhattan'] | None = ..., heuristic_scale: float | None = ..., stats: bool = ..., by_index: bool = ...) -> list[dict[str, Any] | None]
Like :meth:Vertex.shortest_paths; method=None picks "astar" if
heuristic or heuristic_scale is given, "dijkstra" on a weighted
projection, "bfs" otherwise.
With by_index=True, pairs and returned nodelists use integer
positions in ids(). Also accepts an (n, 2) int32/int64 numpy
matrix. Negative, out-of-range, boolean and noninteger indices are
rejected. Default string-id behavior is unchanged.
With stats=True, each found path includes "stats": {"settled": n}.
Counts are Dijkstra settled nodes, A* expansions (including reopens),
or BFS nodes reached; unreachable entries stay None.
"astar" needs a weighted projection with node coordinates
(Vertex.project(coords=...) or from_arrays(coords=...)). It
estimates the remaining cost as heuristic_scale (default 1.0) times
the heuristic distance ("euclidean", the default, or "manhattan")
between the node's and the target's coordinates. Costs equal
"dijkstra"'s when no edge costs less than heuristic_scale times the
distance between its ends (e.g. "manhattan" on a grid with unit steps
and costs of at least 1); a larger scale settles fewer nodes but may
return dearer paths.
Equal-cost paths: walking back from the target, each step goes to
the neighbour with the lowest index (position in ids()) through
which a cheapest route arrives, so the result does not depend on the
order of the edges (from_arrays) or on the number of threads.
"astar" applies this to the nodes it expands (ordered by estimated
total, then larger cost so far, then index): it may pick another of
several equal-cost paths than "dijkstra", but always the same one.
Raises ValueError for an unknown method or heuristic, a negative or non-finite heuristic_scale, A* options with another method, or "astar" on a projection without weights or coordinates.
shortest_path_multi ¶
shortest_path_multi(sources: list[tuple[str, float]], targets: list[tuple[str, float]], method: Literal['dijkstra', 'astar'] | None = ..., *, max_cost: float | None = ..., heuristic: Literal['euclidean', 'manhattan'] | None = ..., heuristic_scale: float | None = ..., goal_coords: Sequence[float] | None = ..., stats: bool = ...) -> dict[str, Any] | None
One search minimizing entry + graph + exit costs. Endpoints are (id, finite nonnegative cost) pairs. Duplicates use the minimum; empty sides return None. Result has nodelist, cost, source, target; stats=True adds stats.settled. max_cost includes entry and exit.
Default method is dijkstra (unit edges on unweighted projections), or astar if an A* option is given. A* needs projection coordinates. Without goal_coords its estimate is min(exit + scaled distance to each target); with goal_coords, scaled distance to that goal. For optimal results edges must dominate scaled metric distances, and exits must dominate scaled distances from targets to the goal. Equal costs prefer the lowest target index, then lowest predecessor at each step that increases represented distance; the virtual source sorts after nodes. Unchanged-distance steps keep the first route to avoid cycles.
distances ¶
distances(sources: list[str], targets: list[str] | None = ..., method: Literal['bfs', 'dijkstra'] | None = ..., *, max_cost: float | None = ...) -> dict[str, dict[str, float]]
Like :meth:Vertex.distances, on this projection ("astar" raises
ValueError: it needs one target per query).
weakly_connected_components ¶
weakly_connected_components(*, by_index: bool = ...) -> list[list[str]] | list[list[int]]
Components ignoring edge direction: lists of ids (indices with by_index=True), largest first.
strongly_connected_components ¶
strongly_connected_components(*, by_index: bool = ...) -> list[list[str]] | list[list[int]]
Strongly connected components along the edges: lists of ids (indices with by_index=True), largest first.
topological_sort ¶
topological_sort() -> list[str]
Ids with every edge pointing forwards (ties in projection order).
Raises ValueError if the projection has a cycle.
find_cycle ¶
find_cycle() -> list[str] | None
One cycle (the last id has an edge back to the first), or None.
degree_centrality ¶
degree_centrality(direction: Literal['out', 'in'] | None = ...) -> dict[str, float]
{id: degree / (n - 1)}, one per edge.
pagerank ¶
pagerank(alpha: float = ..., *, personalization: dict[str, float] | None = ..., max_iter: int = ..., tol: float = ...) -> dict[str, float]
{id: rank}, like networkx.pagerank; uses the projection's weights.
personalization biases the random jumps (personalized PageRank).
Raises ValueError for invalid options or if it does not converge;
tol=0 runs exactly max_iter iterations instead.
clustering ¶
clustering(*, directed: bool = ...) -> dict[str, float]
{id: local clustering coefficient}: edges as undirected (like
networkx), or with directed=True the LDBC Graphalytics definition.
label_propagation ¶
label_propagation(max_iter: int = ...) -> list[list[str]]
Communities by synchronous label propagation (the LDBC CDLP rule; deterministic), largest first.
bfs_levels ¶
bfs_levels(sources: list[str], max_depth: int | None = ...) -> dict[str, int]
{id: hops from the nearest source} for every node reached.
betweenness_centrality ¶
betweenness_centrality(k: int | None = ..., *, normalized: bool = ..., endpoints: bool = ..., weighted: bool | None = ..., seed: int | None = ...) -> dict[str, float]
Betweenness centrality (Brandes; k samples sources), like networkx.
closeness_centrality ¶
closeness_centrality(*, wf_improved: bool = ..., weighted: bool | None = ...) -> dict[str, float]
Closeness centrality from the distances to each node, like networkx.
harmonic_centrality ¶
harmonic_centrality(*, weighted: bool | None = ...) -> dict[str, float]
Sum of 1 / distance from every node that reaches each node.
similarity ¶
similarity(pairs: list[tuple[str, str]], metric: Literal['jaccard', 'overlap', 'common_neighbors', 'adamic_adar', 'resource_allocation', 'preferential_attachment'] = ...) -> list[float]
Neighbourhood similarity of each pair (edges as undirected).
leiden ¶
leiden(resolution: float = ..., *, randomness: float = ..., max_iter: int = ..., seed: int | None = ...) -> list[list[str]]
Communities by the Leiden algorithm (connected, maximising modularity), largest first.
modularity ¶
modularity(communities: Iterable[Iterable[str]], resolution: float = ...) -> float
Modularity of a partition of the nodes, like networkx.community.modularity.
minimum_spanning_tree ¶
minimum_spanning_tree(*, maximum: bool = ...) -> list[tuple[str, str, float]]
Edges (id, id, weight) of a minimum (or maximum) spanning forest.
fastrp ¶
fastrp(dimension: int = ..., *, iteration_weights: list[float] = ..., self_influence: float = ..., normalization_strength: float = ..., seed: int | None = ...) -> dict[str, list[float]]
{id: embedding} by FastRP (fast random projection).
node2vec_walks ¶
node2vec_walks(walk_length: int = ..., walks_per_node: int = ..., *, p: float = ..., q: float = ..., sources: list[str] | None = ..., seed: int | None = ...) -> list[list[str]]
node2vec (second-order biased) random walks.
k_shortest_paths ¶
k_shortest_paths(source: str, target: str, k: int, method: Literal['bfs', 'dijkstra'] | None = ...) -> list[dict[str, Any]]
Up to k shortest loopless paths, cheapest first (Yen).
Each search breaks ties between equal-cost paths like
:meth:shortest_paths (by node index), so the first path is the one
shortest_paths returns and the list is the same every time.
Path ¶
Expr ¶
Filter expression evaluated in Rust (see ironweaver.attr).
attr ¶
attr(path: str | list[str]) -> Attr
An attribute of the node / edge: attr("age") > 30; attr("pos.lat")
reaches into nested dicts, attr(["a.b"]) for names containing dots.
NodeView ¶
NodeView(node: Node)
Lightweight proxy around :class:Node for use in filter lambdas.
Provides a clean, expressive API so that predicates read naturally::
vertex.filter(lambda n: (
n.id.startswith("test_")
and n.type in {"A", "B", "C"}
and n.attr("score") < 0.8
and n.attr("status") != "archived"
))
Attributes¶
id : str
The node identifier.
type : str or None
Shortcut for node.attr["type"].
edges : list[Edge]
Outgoing edges.
inverse_edges : list[Edge]
Incoming edges.
meta : dict
Node metadata.
attrs : dict
The full attribute dictionary (same as node.attr).
node : Node
The underlying :class:Node object.
neighbor_ids
property
¶
neighbor_ids: set[str]
Set of IDs of directly connected outgoing neighbours.
attr ¶
attr(key: str, default: Any = None) -> Any
Return the value of attribute key, or default if missing.
Example¶
n.attr("score") # returns the value or None n.attr("score", 0.0) # returns the value or 0.0
has_edge_to ¶
has_edge_to(target_id: str) -> bool
Return True if this node has an outgoing edge to target_id.
has_edge_from ¶
has_edge_from(source_id: str) -> bool
Return True if this node has an incoming edge from source_id.
EdgeView ¶
EdgeView(edge: Edge)
Lightweight proxy around :class:Edge for use in traversal filter lambdas.
Provides a clean, expressive API so that predicates read naturally::
node.traverse(depth=3, filter=lambda e: e.type == "knows")
Attributes¶
type : str or None
Shortcut for edge.attr.get("type").
from_node : Node
The source node of this edge.
to_node : Node
The target node of this edge.
attrs : dict
The full attribute dictionary (same as edge.attr).
edge : Edge
The underlying :class:Edge object.
attr ¶
attr(key: str, default: Any = None) -> Any
Return the value of attribute key, or default if missing.
ObservedDictionary ¶
A dict-like container that fires per-key callbacks on value changes.