# Graph

relationalai.semantics.reasoners.graph.core

```python
Graph(
    model: Model,
    *,
    directed: bool,
    weighted: bool,
    aggregator: Optional[str] = None,
    node_concept: Optional[Concept] = None,
    edge_concept: Optional[Concept] = None,
    edge_src_relationship: Optional[Relationship | Chain] = None,
    edge_dst_relationship: Optional[Relationship | Chain] = None,
    edge_weight_relationship: Optional[Relationship | Chain] = None
)
```

A graph defined within a PyRel model, over which graph algorithms
can be computed.

Construct a `Graph` to define a graph, then call member methods
(e.g. `degree`, `pagerank`, `louvain`) to compute over it.
Each method returns a `Relationship` containing the results.

There are three ways to construct a graph:

1. **Default arguments only**. `Node` and `Edge` concepts are
   auto-generated by the constructor. `Node` can be populated like
   any other concept via `define(Node.new(...))`. The generated
   `Node` concept extends `AnyEntity`, so instances of existing
   concepts can be identified as nodes via `define(Node(ExistingConcept))`.
   Edges can be populated via
   `define(Edge.new(src=..., dst=..., [weight=...]))`.
   Nodes are also auto-inferred from edge `src`/`dst`
   definitions.
2. **`node_concept` only**. The provided concept is assigned
   directly as `graph.Node` (i.e., `graph.Node is node_concept`).
   An `Edge` concept is still generated and must be populated.
3. **`node_concept` + `edge_concept` + relationships**. Both
   concepts are user-provided. The edge source, destination, and
   (if weighted) weight relationships must also be supplied.

As with all PyRel `Concept`s, properties passed to `Node.new(...)`
and `Edge.new(...)` contribute to entity identity. For auto-generated
`Edge`s, its type also contributes to its identity, so subtypes of
`Edge` (e.g., `Friendship` and `Transaction`, which both extend
`Edge`) with the same properties define distinct edges. Distinct
edges with the same `src` and `dst` are considered "multi-edges".

Multi-edge handling is controlled by the `aggregator` parameter:

- `None` (default): multi-edges produce a PyRel `Error` for all
  methods except `num_nodes()`.
  The PyRel `Error` is shown as a Python warning. Multi-edges
  are then aggregated as in the `"sum"` aggregator case.
- `"sum"`: multi-edges are collapsed into a single edge; weights
  are summed for weighted graphs, or the effective weight becomes
  1.0 for unweighted graphs.

If the graph is weighted:

1. A weight must be provided for each edge. If an edge is provided without a weight,
   a PyRel `Error` is derived, and the edge's weight is normalized to `1.0`.
2. Weights must be `Float`s. If a non-`Float` weight is provided, an exception is
   thrown (a `ValueError` if the weight is provided via `edge_weight_relationship`,
   or a `RAIException` if the weight is provided via an `Edge.new(..., weight=...)`
   definition).
3. Negative, `Inf`, and `NaN` weights are disallowed. If a negative, `Inf`, or
   `NaN` weight is provided, a PyRel `Error` is derived, and the offending weight
   is normalized to `1.0`.

Note that the weight normalizations in (1) and (3) above happen before aggregation
of weights within multi-edges. For example, a multi-edge consisting of two edges,
one with a negative weight and the other with an `Inf` weight, has its constituent
edge weights each normalized to `1.0` and then aggregated to a single edge with
weight `2.0`.

## Parameters

- `model` (`Model`) - The model to use for the graph.
- `directed` (`bool`) - Whether the graph is directed.
- `weighted` (`bool`) - Whether the graph is weighted.
- `aggregator` (`str` | `None`, default: `None`) - Multi-edge handling mode. `None` (default) derives an `Error` when multi-edges are present and any method except `num_nodes()` is called. It then aggregates the edges as in the `"sum"` case. `"sum"` aggregates multi-edges into a single edge with summed weights (weighted) or effective weight 1.0 (unweighted).
- `node_concept` (`Concept` | `None`, default: `None`) - The concept to use for the nodes in the graph.
- `edge_concept` (`Concept` | `None`, default: `None`) - The concept to use for the edges in the graph.
- `edge_src_relationship` (`Relationship` | `Chain` | `None`, default: `None`) - The relationship for edge source nodes. Must be a binary relationship with first field matching `edge_concept` and second field matching `node_concept`.
- `edge_dst_relationship` (`Relationship` | `Chain` | `None`, default: `None`) - The relationship for edge destination nodes. Must be a binary relationship with first field matching `edge_concept` and second field matching `node_concept`.
- `edge_weight_relationship` (`Relationship` | `Chain` | `None`, default: `None`) - The relationship for edge weights. Must be a binary relationship with first field matching `edge_concept` and second field of type `Float`.

## Examples

Build a graph using auto-generated `Node` and `Edge` concepts
(the default):

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Create a model and graph with auto-generated Node and Edge concepts.
model = Model("example")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges forming an undirected path graph 1-2-3.
n1, n2, n3 = Node.new(id=1), Node.new(id=2), Node.new(id=3)
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
)

# 3. Compute and inspect the degree of each node.
degree = graph.degree()
model.select(Node.id, Integer).where(degree(Node, Integer)).inspect()
#   id  number
# 0  1       1
# 1  2       2
# 2  3       1
```

Build a graph using a user-provided `node_concept` and create edges
individually:

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Create a model with a Person concept and instances.
model = Model("node_concept_example")
Person = model.Concept("Person")
jack = Person.new(name="Jack")
jill = Person.new(name="Jill")
john = Person.new(name="John")
model.define(jack, jill, john)

# 2. Create a directed graph with existing Person concept as the node concept.
#    The Edge concept is auto-generated.
graph = Graph(model, directed=True, weighted=False, node_concept=Person)

# 3. Define edges using the auto-generated Edge concept.
model.define(
    graph.Edge.new(src=jack, dst=jill),
    graph.Edge.new(src=jill, dst=john),
)

# 4. Compute and inspect the distance from Jill to reachable nodes.
distance = graph.distance(full=True)
src, dst, length = graph.Node.ref(), graph.Node.ref(), Integer.ref("length")
model.where(distance(src, dst, length), src.name == "Jill").select(
    src.name.alias("src_name"), dst.name.alias("dst_name"), length
).inspect()
#   src_name dst_name  length
# 0     Jill     Jill       0
# 1     Jill     John       1
```

Build a graph from user-provided `node_concept`, `edge_concept`, and
`edge_*_relationship` arguments:

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Create a model with Person and Transaction concepts.
model = Model("edge_concept_example")
Person = model.Concept("Person")
Transaction = model.Concept("Transaction")
Transaction.payer = model.Relationship(
    f"{Transaction:transaction} has payer {Person:payer}"
)
Transaction.payee = model.Relationship(
    f"{Transaction:transaction} has payee {Person:payee}"
)
Transaction.amount = model.Relationship(
    f"{Transaction:transaction} has amount {Float:amount}"
)

# 2. Define Person and Transaction instances.
jack = Person.new(name="Jack")
jill = Person.new(name="Jill")
john = Person.new(name="John")
model.define(jack, jill, john)
model.define(
    Transaction.new(payer=jack, payee=jill, amount=100.0),
    Transaction.new(payer=jill, payee=john, amount=200.0),
)

# 3. Create a graph using the user-provided concepts and relationships.
graph = Graph(
    model,
    directed=True,
    weighted=True,
    node_concept=Person,
    edge_concept=Transaction,
    edge_src_relationship=Transaction.payer,
    edge_dst_relationship=Transaction.payee,
    edge_weight_relationship=Transaction.amount,
)

# 4. Compute and inspect the weighted outdegree of each Person node.
weighted_outdegree = graph.weighted_outdegree()
model.where(weighted_outdegree(Person, Float)).select(
    Person.name, Float.alias("Outgoing Transaction Total")
).inspect()
#   name  Outgoing Transaction Total
# 0 Jack                       100.0
# 1 Jill                       200.0
# 2 John                         0.0
```

An alternative to the above is to represent the same graph using an existing
relationship alongside a user-provided `node_concept`:

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Create a model with Person and Transaction concepts.
model = Model("edge_concept_example")
Person = model.Concept("Person")
transaction_relationship = model.Relationship(
    f"{Person:payer} paid {Person:payee} the amount of {Float:amount}"
)

# 2. Define Person and Transaction instances.
jack = Person.new(name="Jack")
jill = Person.new(name="Jill")
john = Person.new(name="John")
model.define(jack, jill, john)
model.define(
    transaction_relationship(jack, jill, 100.0),
    transaction_relationship(jill, john, 200.0),
)

# 3. Create a graph using the user-provided concepts and relationships.
graph = Graph(
    model,
    directed=True,
    weighted=True,
    node_concept=Person,
)
model.define(
    graph.Edge.new(
        src=transaction_relationship["payer"],
        dst=transaction_relationship["payee"],
        weight=transaction_relationship["amount"],
    )
)

# 4. Compute and inspect the weighted outdegree of each Person node.
weighted_outdegree = graph.weighted_outdegree()
model.where(weighted_outdegree(Person, Float)).select(
    Person.name, Float.alias("Outgoing Transaction Total")
).inspect()
#   name  Outgoing Transaction Total
# 0 Jack                       100.0
# 1 Jill                       200.0
# 2 John                         0.0
```

You can use an optional `aggregator` argument to control how multi-edges are handled.

```python
# 1. Create a graph with multi-edges and an aggregator.
model = Model("multi_edge_with_aggregator_example")
graph = Graph(model, directed=True, weighted=True, aggregator="sum")
n1, n2 = graph.Node.new(id=1), graph.Node.new(id=2)
model.define(n1, n2)
model.define(
    graph.Edge.new(src=n1, dst=n2, weight=0.13),
    graph.Edge.new(src=n1, dst=n2, weight=4.2),
)

# Multi-edges can be queried via `self.Edge`.
model.select(
    graph.Edge.src.id.alias("src_id"),
    graph.Edge.dst.id.alias("dst_id"),
).inspect()
#   src_id dst_id
# 0      1      2
# 1      1      2
# Algorithms aggregate the multi-edges to a single edge by summing the weights
graph.num_edges().inspect()
#   num_edges
# 0         1
model.where(graph.distance(full=True)(n1, n2, Float)).select(
    Float.alias("distance_n1_to_n2")
).inspect()
#    distance_n1_to_n2
# 0               4.33
model.where(graph.weighted_degree()(n1, Float)).select(
    Float.alias("weighted_degree_n1")
).inspect()
#    weighted_degree_n1
# 0                4.33

# 2. Create a graph with multi-edges and no aggregator.
model = Model("multi_edge_without_aggregator_example")
graph = Graph(model, directed=True, weighted=True)  # Aggregator defaults to None.
n1, n2 = graph.Node.new(id=1), graph.Node.new(id=2)
model.define(n1, n2)
model.define(
    graph.Edge.new(src=n1, dst=n2, weight=0.13),
    graph.Edge.new(src=n1, dst=n2, weight=4.2),
)

# Multi-edges can still be queried and do not produce any warnings.
from warnings import catch_warnings, simplefilter

simplefilter("always")
with catch_warnings(record=True) as caught_warnings:
    model.select(
        graph.Edge.src.id.alias("src_id"),
        graph.Edge.dst.id.alias("dst_id"),
    ).inspect()
#   src_id dst_id
# 0      1      2
# 1      1      2
len(caught_warnings)
# 0
# In the presence of multi-edges when `aggregator=None`, `Error` concept is derived
# for every method except `num_nodes()`. This in
# turn produces a Python warning.
with catch_warnings(record=True) as caught_warnings:
    result1 = graph.num_edges().to_df()
    result2 = (
        model.where(graph.distance(full=True)(n1, n2, Float))
        .select(Float.alias("distance_n1_to_n2"))
        .to_df()
    )
    result3 = (
        model.where(graph.weighted_degree()(n1, Float))
        .select(Float.alias("weighted_degree_n1"))
        .to_df()
    )
len(caught_warnings)
# 3
caught_warnings[0].message.message[:50]
# 'Multi-edges are not allowed when `aggregator=None`'
# If you _do_ intend to have multi-edges, you should set `aggregator="sum"` and avoid the warnings.
# For convenience, the multi-edges are still turned into edges even for the `aggregator=None` case, but
# we do not recommend relying on this behaviour in production.
result1
#   num_edges
# 0         1
result2
#    distance_n1_to_n2
# 0               4.33
result3
#    weighted_degree_n1
# 0                4.33
# 7. Create a graph with invalid weights.
model = Model("invalid_weights_example")
graph = Graph(model, directed=True, weighted=True)
n1, n2 = graph.Node.new(id=1), graph.Node.new(id=2)
model.define(n1, n2)
model.define(
    graph.Edge.new(src=n1, dst=n2, weight=-1.0),
    graph.Edge.new(src=n2, dst=n1, weight=float("inf")),
)
src, dst = graph.Node.ref(), graph.Node.ref()
with catch_warnings(record=True) as caught_warnings:
    model.select(src.id, dst.id, Float).where(graph._weight(src, dst, Float)).inspect()
#    id id_2  float
# 0   1    2    1.0
# 1   2    1    1.0
```

## Attributes

### .`directed`

```python
Graph.directed: bool
```

Whether the graph is directed.

### .`weighted`

```python
Graph.weighted: bool
```

Whether the graph is weighted.

### .`Node`

```python
Graph.Node: Concept
```

The nodes of the graph.

### .`Edge`

```python
Graph.Edge: Concept
```

The edges of the graph. This concept does not take the aggregator into
consideration, and hence multi-edges are returned for a multi-graph.

### .`EdgeSrc`

```python
Graph.EdgeSrc: Relationship | Chain
```

Binary relationship that for each edge `Edge` contains the corresponding source `Node`.

**Possible Members:**

- `Relationship`
- `Chain`

### .`EdgeDst`

```python
Graph.EdgeDst: Relationship | Chain
```

Binary relationship that for each edge `Edge` contains the corresponding destination `Node`.

**Possible Members:**

- `Relationship`
- `Chain`

### .`EdgeWeight`

```python
Graph.EdgeWeight: Relationship | Chain
```

Binary relationship that for each edge `Edge` contains a `Float` representing the
weight of the edge.
Note that this relationship does not take the aggregator into consideration.

**Possible Members:**

- `Relationship`
- `Chain`

## Methods

### .`num_nodes`()

```python
Graph.num_nodes() -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a unary relationship containing the number of nodes in the graph.

**Returns:**

- `Relationship` - A unary relationship containing the number of nodes in the graph.

**Relationship Schema:**

`num_nodes(count)`

- **count** (*Integer*): The number of nodes in the graph.

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up the graph and concepts
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define some nodes
node1, node2, node3, node4 = [Node.new(id=i) for i in range(1, 5)]
model.define(node1, node2, node3, node4)

# 3. Define the full set of edges
model.define(
    Edge.new(src=node1, dst=node2),
    Edge.new(src=node2, dst=node3),
    Edge.new(src=node3, dst=node3),
    Edge.new(src=node2, dst=node4),
)

# 4. The relationship contains the number of nodes
graph.num_nodes().inspect()
#   num_nodes
# 0         4
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`num_edges`()

```python
Graph.num_edges() -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a unary relationship containing the number of edges in the graph.

**Returns:**

- `Relationship` - A unary relationship containing the number of edges in the graph.

**Relationship Schema:**

`num_edges(count)`

- **count** (*Integer*): The number of edges in the graph.

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up the graph and concepts
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define some nodes
node1, node2, node3, node4 = [Node.new(id=i) for i in range(1, 5)]
model.define(node1, node2, node3, node4)

# 3. Define the edges
model.define(
    Edge.new(src=node1, dst=node2),
    Edge.new(src=node2, dst=node3),
    Edge.new(src=node3, dst=node3),
    Edge.new(src=node2, dst=node4),
)

# 4. The relationship contains the number of edges
graph.num_edges().inspect()
#   num_edges
# 0         4
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`neighbor`()

```python
Graph.neighbor(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Same as the union of `inneighbor` and `outneighbor`.

Weighted

✔

Weights are ignored.

Returns a binary relationship containing all neighbor pairs in the graph.

For directed graphs, a node's neighbors include both its in-neighbors
and out-neighbors.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the neighbor computation: only neighbors of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and one
  of its neighbors.

**Relationship Schema:**

`neighbor(node, neighbor_node)`

- **node** (*Node*): A node in the graph.
- **neighbor\_node** (*Node*): A neighbor of the node.

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the IDs from the neighbor relationship and inspect
u, v = Node.ref("u"), Node.ref("v")
neighbor = graph.neighbor()
model.select(u.id, v.id).where(neighbor(u, v)).inspect()
#   id id_2
# 0  1    2
# 1  2    1
# 2  2    3
# 3  2    4
# 4  3    2
# 5  3    3
# 6  4    2
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute neighbors of
# Define a subset containing only nodes 2 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))

# Get neighbors only of nodes in the subset
constrained_neighbor = graph.neighbor(of=subset)
model.select(u.id, v.id).where(constrained_neighbor(u, v)).inspect()
#   id id_2
# 0  2    1
# 1  2    3
# 2  2    4
# 3  3    2
# 4  3    3
```

**Notes:**

The relationship returned by `neighbor(...)` is cached for a given set of arguments.
All `neighbor(...)` calls with the same arguments will return the same relationship.

The `neighbor()` method, called with no parameters, computes
the full neighbor relationship. In contrast, `neighbor(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the neighbor relation is needed
across a program, `neighbor()` is typically more efficient; this is the
typical case. Use `neighbor(of=subset)` only when small subsets of the
neighbor relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`inneighbor`()

```python
Graph.inneighbor(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Same as `neighbor`.

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship of all nodes and their in-neighbors.

An in-neighbor of a node `u` is any node `v` where an edge from `v`
to `u` exists. For undirected graphs, this is identical to `neighbor`.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the inneighbor computation: only in-neighbors of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a destination node
  and one of its in-neighbors.

**Relationship Schema:**

`inneighbor(node, inneighbor_node)`

- **node** (*Node*): The destination node.
- **inneighbor\_node** (*Node*): The in-neighbor of the node (i.e., the source of an incoming edge).

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the IDs from the in-neighbor relationship and inspect
node, inneighbor_node = Node.ref("node"), Node.ref("inneighbor_node")
inneighbor = graph.inneighbor()
model.select(node.id, inneighbor_node.id).where(
    inneighbor(node, inneighbor_node)
).inspect()
#   id id_2
# 0  2    1
# 1  3    2
# 2  3    3
# 3  4    2
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute in-neighbors of
# Define a subset containing only nodes 2 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))

# Get in-neighbors only of nodes in the subset
constrained_inneighbor = graph.inneighbor(of=subset)
model.select(node.id, inneighbor_node.id).where(
    constrained_inneighbor(node, inneighbor_node)
).inspect()
#   id id_2
# 0  2    1
# 1  3    2
# 2  3    3
```

**Notes:**

The relationship returned by `inneighbor(...)` is cached for a given set of arguments.
All `inneighbor(...)` calls with the same arguments will return the same relationship.

The `inneighbor()` method, called with no parameters, computes
the full inneighbor relationship. In contrast, `inneighbor(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the inneighbor relation is needed
across a program, `inneighbor()` is typically more efficient; this is the
typical case. Use `inneighbor(of=subset)` only when small subsets of the
inneighbor relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`outneighbor`()

```python
Graph.outneighbor(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Same as `neighbor`.

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship of all nodes and their out-neighbors.

An out-neighbor of a node `u` is any node `v` where an edge from `u`
to `v` exists. For undirected graphs, this is identical to `neighbor`.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the outneighbor computation: only out-neighbors of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a source node
  and one of its out-neighbors.

**Relationship Schema:**

`outneighbor(node, outneighbor_node)`

- **node** (*Node*): The source node.
- **outneighbor\_node** (*Node*): The out-neighbor of the node (i.e., the destination of an outgoing edge).

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the IDs from the out-neighbor relationship and inspect
node, outneighbor_node = Node.ref("node"), Node.ref("outneighbor_node")
outneighbor = graph.outneighbor()
model.select(node.id, outneighbor_node.id).where(
    outneighbor(node, outneighbor_node)
).inspect()
#   id id_2
# 0  1    2
# 1  2    3
# 2  2    4
# 3  3    3
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute out-neighbors of
# Define a subset containing only nodes 2 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))

# Get out-neighbors only of nodes in the subset
constrained_outneighbor = graph.outneighbor(of=subset)
model.select(node.id, outneighbor_node.id).where(
    constrained_outneighbor(node, outneighbor_node)
).inspect()
#   id id_2
# 0  2    3
# 1  2    4
# 2  3    3
```

**Notes:**

The relationship returned by `outneighbor(...)` is cached for a given set of arguments.
All `outneighbor(...)` calls with the same arguments will return the same relationship.

The `outneighbor()` method, called with no parameters, computes
the full outneighbor relationship. In contrast, `outneighbor(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the outneighbor relation is needed
across a program, `outneighbor()` is typically more efficient; this is the
typical case. Use `outneighbor(of=subset)` only when small subsets of the
outneighbor relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`common_neighbor`()

```python
Graph.common_neighbor(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a ternary relationship of common neighbor triplets.

A node `w` is a common neighbor of a pair of nodes `u` and `v` if
`w` is a neighbor of both `u` and `v`.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes common neighbors for all pairs of nodes in the graph. This computation can be expensive for large graphs, as the result can scale quadratically in the number of edges or cubically in the number of nodes. Mutually exclusive with other parameters. Default is `None`.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the common neighbor computation: only common neighbors of node pairs where the first node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. Can only be used together with the `from_` parameter. When provided with `from_`, constrains the domain of the common neighbor computation: only common neighbors of node pairs where the first node is in `from_` and the second node is in `to` are computed and returned. Default is `None`.
- `between` (`Relationship`, default: `None`) - A binary relationship containing pairs of nodes. When provided, constrains the domain of the common neighbor computation: only common neighbors for the specific node pairs in this relationship are computed and returned. Mutually exclusive with other parameters. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a pair of nodes
  and one of their common neighbors.

**Raises:**

- `TypeError` - If `from_`, `to`, or `between` is not a `Relationship`.
- `ValueError` - If `full` is provided with any other parameter.
  If `between` is provided with any other parameter.
  If `from_` is provided with any parameter other than `to`.
  If `to` is provided without the `from_` parameter.
  If none of `full`, `from_`, or `between` is provided.
  If `full` is not `True` or `None`.
  If `from_`, `to`, or `between` is not attached to the same model as the graph.
  If `from_`, `to`, or `between` does not contain the graph's `Node` concept.
  If `from_` or `to` is not a unary relationship.
  If `between` is not a binary relationship.

**Relationship Schema:**

`common_neighbor(node_u, node_v, common_neighbor_node)`

- **node\_u** (*Node*): The first node in the pair.
- **node\_v** (*Node*): The second node in the pair.
- **common\_neighbor\_node** (*Node*): The common neighbor of the pair.

**Examples:**

```python
from relationalai.semantics import Model, define, select
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)

# 3. Select the IDs from the common_neighbor relationship and inspect
u, v, w = Node.ref("u"), Node.ref("v"), Node.ref("w")
common_neighbor = graph.common_neighbor(full=True)
model.select(u.id, v.id, w.id).where(common_neighbor(u, v, w)).inspect()
#     id  id_2  id_3
# 0    1    1    2
# 1    1    3    2
# 2    1    4    2
# 3    2    2    1
# 4    2    2    3
# 5    2    2    4
# 6    2    3    3
# 7    2    3    4
# 8    2    4    3
# 9    3    1    2
# 10   3    2    3
# 11   3    2    4
# 12   3    3    2
# 13   3    3    3
# 14   3    3    4
# 15   3    4    2
# 16   3    4    3
# 17   4    1    2
# 18   4    2    3
# 19   4    3    2
# 20   4    3    3
# 21   4    4    2
# 22   4    4    3
```

```python
# 4. Use 'from_' parameter to constrain the set of nodes to compute common neighbors for
# Define a subset containing only node 1
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(node.id == 1).define(subset(node))

# Get common neighbors only for pairs where first node is in subset
constrained_common_neighbor = graph.common_neighbor(from_=subset)
model.select(u.id, v.id, w.id).where(constrained_common_neighbor(u, v, w)).inspect()
#    id  id_2  id_3
# 0   1    1    2
# 1   1    3    2
# 2   1    4    2
```

```python
# 5. Use both 'from_' and 'to' parameters to constrain the first two positions
subset_a = model.Relationship(f"{Node:node} is in subset_a")
subset_b = model.Relationship(f"{Node:node} is in subset_b")
model.where(node.id == 1).define(subset_a(node))
model.where(node.id == 3).define(subset_b(node))

# Get common neighbors only where the first node is in subset_a and the second node is in subset_b
constrained_common_neighbor = graph.common_neighbor(from_=subset_a, to=subset_b)
model.select(u.id, v.id, w.id).where(constrained_common_neighbor(u, v, w)).inspect()
#    id  id_2  id_3
# 0   1    3    2
```

```python
# 6. Use 'between' parameter to constrain to specific pairs of nodes
pairs = model.Relationship(f"{Node:node_a} and {Node:node_b} are a pair")
node_a, node_b = Node.ref(), Node.ref()
model.where(node_a.id == 1, node_b.id == 3).define(pairs(node_a, node_b))
model.where(node_a.id == 2, node_b.id == 4).define(pairs(node_a, node_b))

# Get common neighbors only for the specific pairs (1, 3) and (2, 4)
constrained_common_neighbor = graph.common_neighbor(between=pairs)
model.select(u.id, v.id, w.id).where(constrained_common_neighbor(u, v, w)).inspect()
#    id  id_2  id_3
# 0   1    3    2
# 1   2    4    3
```

**Notes:**

The relationship returned by `common_neighbor(...)` is cached for a given set of arguments.
All `common_neighbor(...)` calls with the same arguments will return the same relationship.

The `common_neighbor(full=True)` method computes the full common
neighbor relationship for all pairs of nodes. This can be expensive as the
result can contain O(|E|²) or O(|V|³) tuples depending on graph density.

Calling `common_neighbor()` without arguments raises a `ValueError`,
to ensure awareness and explicit acknowledgement (`full=True`) of this cost.

In contrast, `common_neighbor(from_=subset)` constrains the computation to
tuples with the first position in the passed-in `subset`. When a
significant fraction of the common neighbor relation is needed across a
program, `common_neighbor(full=True)` is typically more efficient. Use
`common_neighbor(from_=subset)` only when small subsets of the common
neighbor relationship are needed collectively across the program.

The `to` parameter can be used together with `from_` to further
constrain the computation: `common_neighbor(from_=subset_a, to=subset_b)`
computes common neighbors only for node pairs where the first node is in
`subset_a` and the second node is in `subset_b`. (Since `common_neighbor`
is symmetric in its first two positions, using `to` without `from_` would
be functionally redundant, and is not allowed.)

The `between` parameter provides another way to constrain the computation:
Unlike `from_` and `to`, which allow you to independently constrain the first
and second positions in `common_neighbor` tuples to sets of nodes, `between`
allows you to constrain the first and second positions, jointly, to specific pairs
of nodes.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`degree`()

```python
Graph.degree(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship containing the degree of each node.

For directed graphs, a node's degree is the sum of its indegree and
outdegree. For undirected graphs, a self-loop contributes +2 to the
node's degree.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the degree computation: only degrees of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  degree.

**Relationship Schema:**

`degree(node, node_degree)`

- **node** (*Node*): The node.
- **node\_degree** (*Integer*): The degree of the node.

**Examples:**

**Undirected Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the degree of each node and inspect
node, node_degree = Node.ref("node"), Integer.ref("node_degree")
degree = graph.degree()
model.select(node.id, node_degree).where(degree(node, node_degree)).inspect()
#    id  node_degree
# 0   1            1
# 1   2            3
# 2   3            3
# 3   4            1
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute degree of
# Define a subset containing only nodes 2 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))

# Get degrees only of nodes in the subset
constrained_degree = graph.degree(of=subset)
model.select(node.id, node_degree).where(
    constrained_degree(node, node_degree)
).inspect()
#    id  node_degree
# 0   2            3
# 1   3            3
```

**Directed Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define the same nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the degree of each node and inspect
node, node_degree = Node.ref("node"), Integer.ref("node_degree")
degree = graph.degree()
model.select(node.id, node_degree).where(degree(node, node_degree)).inspect()
#    id  node_degree
# 0   1            1
# 1   2            3
# 2   3            3
# 3   4            1
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute degree of
# Define a subset containing only nodes 1 and 4
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 4)).define(subset(node))

# Get degrees only of nodes in the subset
constrained_degree = graph.degree(of=subset)
model.select(node.id, node_degree).where(
    constrained_degree(node, node_degree)
).inspect()
#    id  node_degree
# 0   1            1
# 1   4            1
```

**Notes:**

The relationship returned by `degree(...)` is cached for a given set of arguments.
All `degree(...)` calls with the same arguments will return the same relationship.

The `degree()` method, called with no parameters, computes
the full degree relationship. In contrast, `degree(of=subset)` computes a
constrained relationship specific to the passed-in `subset`. When
a significant fraction of the degree relation is needed
across a program, `degree()` is typically more efficient; this is the
typical case. Use `degree(of=subset)` only when small subsets of the
degree relationship are needed collectively across the program.

**Self-loops** contribute +2 to the degree of a node.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Use a graph algorithm](/build/reasoning/graph/run-an-algorithm/index.md#use-a-graph-algorithm)
            2. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`indegree`()

```python
Graph.indegree(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Identical to `degree`, except for self-loops.

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship containing the indegree of each node.

A node's indegree is the number of incoming edges. For undirected
graphs, a node's indegree is identical to its degree, except self-loops
contribute only +1 to a node's indegree.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the indegree computation: only indegrees of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  indegree.

**Relationship Schema:**

`indegree(node, node_indegree)`

- **node** (*Node*): The node.
- **node\_indegree** (*Integer*): The indegree of the node.

**Examples:**

**Undirected Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n3, dst=n4),
)
# 3. Select the indegree of each node and inspect
node, node_indegree = Node.ref("node"), Integer.ref("node_indegree")
indegree = graph.indegree()
model.select(node.id, node_indegree).where(indegree(node, node_indegree)).inspect()
#    id  node_indegree
# 0   1              1
# 1   2              2
# 2   3              3
# 3   4              1

# 4. Use 'of' parameter to constrain the set of nodes to compute indegree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))
constrained_indegree = graph.indegree(of=subset)
model.select(node.id, node_indegree).where(
    constrained_indegree(node, node_indegree)
).inspect()
#    id  node_indegree
# 0   2              2
# 1   3              3
```

**Directed Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define the same nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n3, dst=n4),
)

# 3. Select the indegree of each node and inspect
node, node_indegree = Node.ref("node"), Integer.ref("node_indegree")
indegree = graph.indegree()
model.select(node.id, node_indegree).where(indegree(node, node_indegree)).inspect()
#    id  node_indegree
# 0   1              0
# 1   2              1
# 2   3              2
# 3   4              1

# 4. Use 'of' parameter to constrain the set of nodes to compute indegree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))
constrained_indegree = graph.indegree(of=subset)
model.select(node.id, node_indegree).where(
    constrained_indegree(node, node_indegree)
).inspect()
#    id  node_indegree
# 0   2              1
# 1   3              2
```

**Notes:**

The relationship returned by `indegree(...)` is cached for a given set of arguments.
All `indegree(...)` calls with the same arguments will return the same relationship.

The `indegree()` method, called with no parameters, computes
the full indegree relationship. In contrast, `indegree(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the indegree relation is needed
across a program, `indegree()` is typically more efficient; this is the
typical case. Use `indegree(of=subset)` only when small subsets of the
indegree relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`outdegree`()

```python
Graph.outdegree(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Identical to `degree`, except for self-loops.

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship containing the outdegree of each node.

A node's outdegree is the number of outgoing edges. For undirected
graphs, a node's outdegree is identical to its degree, except self-loops
contribute only +1 to a node's outdegree.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the outdegree computation: only outdegrees of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  outdegree.

**Relationship Schema:**

`outdegree(node, node_outdegree)`

- **node** (*Node*): The node.
- **node\_outdegree** (*Integer*): The outdegree of the node.

**Examples:**

**Undirected Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the outdegree of each node and inspect
node, node_outdegree = Node.ref("node"), Integer.ref("node_outdegree")
outdegree = graph.outdegree()
model.select(node.id, node_outdegree).where(outdegree(node, node_outdegree)).inspect()
#     id  node_outdegree
# 0   1               1
# 1   2               3
# 2   3               2
# 3   4               1

# 4. Use 'of' parameter to constrain the set of nodes to compute outdegree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))
constrained_outdegree = graph.outdegree(of=subset)
model.select(node.id, node_outdegree).where(
    constrained_outdegree(node, node_outdegree)
).inspect()
#    id  node_outdegree
# 0   2               3
# 1   3               2
```

**Directed Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define the same nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the outdegree of each node and inspect
node, node_outdegree = Node.ref("node"), Integer.ref("node_outdegree")
outdegree = graph.outdegree()
model.select(node.id, node_outdegree).where(outdegree(node, node_outdegree)).inspect()
#    id  node_outdegree
# 0   1               1
# 1   2               2
# 2   3               1
# 3   4               0

# 4. Use 'of' parameter to constrain the set of nodes to compute outdegree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))
constrained_outdegree = graph.outdegree(of=subset)
model.select(node.id, node_outdegree).where(
    constrained_outdegree(node, node_outdegree)
).inspect()
#    id  node_outdegree
# 0   2               2
# 1   3               1
```

**Notes:**

The relationship returned by `outdegree(...)` is cached for a given set of arguments.
All `outdegree(...)` calls with the same arguments will return the same relationship.

The `outdegree()` method, called with no parameters, computes
the full outdegree relationship. In contrast, `outdegree(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the outdegree relation is needed
across a program, `outdegree()` is typically more efficient; this is the
typical case. Use `outdegree(of=subset)` only when small subsets of the
outdegree relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`weighted_degree`()

```python
Graph.weighted_degree(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Unweighted

✔

Edge weights are considered to be 1.0.

Returns a binary relationship containing the weighted degree of each node.

A node's weighted degree is the sum of the weights of all edges
connected to it. For directed graphs, this is the sum of the weights
of both incoming and outgoing edges. For undirected graphs, the weights
of self-loops contribute twice to the node's weighted degree. For
unweighted graphs, all edge weights are considered to be 1.0.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the weighted degree computation: only weighted degrees of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  weighted degree.

**Relationship Schema:**

`weighted_degree(node, node_weighted_degree)`

- **node** (*Node*): The node.
- **node\_weighted\_degree** (*Float*): The weighted degree of the node.

**Examples:**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed, weighted graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n2, dst=n1, weight=0.0),
    Edge.new(src=n2, dst=n3, weight=1.0),
)

# 3. Select the weighted degree of each node and inspect
node, node_weighted_degree = Node.ref("node"), Float.ref("node_weighted_degree")
weighted_degree = graph.weighted_degree()
model.select(node.id, node_weighted_degree).where(
    weighted_degree(node, node_weighted_degree)
).inspect()
#     id  node_weighted_degree
# 0   1                   1.0
# 1   2                   2.0
# 2   3                   1.0

# 4. Use 'of' parameter to constrain the set of nodes to compute weighted degree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))
constrained_weighted_degree = graph.weighted_degree(of=subset)
model.select(node.id, node_weighted_degree).where(
    constrained_weighted_degree(node, node_weighted_degree)
).inspect()
#     id  node_weighted_degree
# 0   2                   2.0
# 1   3                   1.0
```

**Notes:**

The relationship returned by `weighted_degree(...)` is cached for a given set of arguments.
All `weighted_degree(...)` calls with the same arguments will return the same relationship.

The `weighted_degree()` method, called with no parameters, computes
the full weighted degree relationship. In contrast, `weighted_degree(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the weighted degree relation is needed
across a program, `weighted_degree()` is typically more efficient; this is the
typical case. Use `weighted_degree(of=subset)` only when small subsets of the
weighted degree relationship are needed collectively across the program.

**Self-loops** contribute twice to the weighted degree of a node.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`weighted_indegree`()

```python
Graph.weighted_indegree(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Identical to `weighted_degree`, except for self-loops.

Directed

✔

Weighted

✔

Unweighted

✔

Edge weights are considered to be 1.0.

Returns a binary relationship containing the weighted indegree of each node.

A node's weighted indegree is the sum of the weights of all incoming
edges. For undirected graphs, this is identical to `weighted_degree`,
except for self-loops. For weighted graphs, we assume edge weights are
non-negative. For unweighted graphs, all edge weights are considered
to be 1.0.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the weighted indegree computation: only weighted indegrees of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  weighted indegree.

**Relationship Schema:**

`weighted_indegree(node, node_weighted_indegree)`

- **node** (*Node*): The node.
- **node\_weighted\_indegree** (*Float*): The weighted indegree of the node.

**Examples:**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed, weighted graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n2, dst=n1, weight=0.0),
    Edge.new(src=n2, dst=n3, weight=1.0),
)

# 3. Select the weighted indegree of each node and inspect
node, node_weighted_indegree = Node.ref("node"), Float.ref("node_weighted_indegree")
weighted_indegree = graph.weighted_indegree()
model.select(node.id, node_weighted_indegree).where(
    weighted_indegree(node, node_weighted_indegree)
).inspect()
#     id  node_weighted_indegree
# 0   1                     0.0
# 1   2                     1.0
# 2   3                     1.0

# 4. Use 'of' parameter to constrain the set of nodes to compute weighted indegree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))
constrained_weighted_indegree = graph.weighted_indegree(of=subset)
model.select(node.id, node_weighted_indegree).where(
    constrained_weighted_indegree(node, node_weighted_indegree)
).inspect()
#     id  node_weighted_indegree
# 0   2                     1.0
# 1   3                     1.0
```

**Notes:**

The relationship returned by `weighted_indegree(...)` is cached for a given set of arguments.
All `weighted_indegree(...)` calls with the same arguments will return the same relationship.

The `weighted_indegree()` method, called with no parameters, computes
the full weighted indegree relationship. In contrast, `weighted_indegree(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the weighted indegree relation is needed
across a program, `weighted_indegree()` is typically more efficient; this is the
typical case. Use `weighted_indegree(of=subset)` only when small subsets of the
weighted indegree relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`weighted_outdegree`()

```python
Graph.weighted_outdegree(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Identical to `weighted_degree`, except for self-loops.

Directed

✔

Weighted

✔

Unweighted

✔

Edge weights are considered to be 1.0.

Returns a binary relationship containing the weighted outdegree of each node.

A node's weighted outdegree is the sum of the weights of all outgoing
edges. For undirected graphs, this is identical to `weighted_degree`,
except for self-loops. For unweighted graphs, all edge weights are
considered to be 1.0.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the weighted outdegree computation: only weighted outdegrees of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  weighted outdegree.

**Relationship Schema:**

`weighted_outdegree(node, node_weighted_outdegree)`

- **node** (*Node*): The node.
- **node\_weighted\_outdegree** (*Float*): The weighted outdegree of the node.

**Examples:**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed, weighted graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n2, dst=n1, weight=0.0),
    Edge.new(src=n2, dst=n3, weight=1.0),
)

# 3. Select the weighted outdegree of each node and inspect
node, node_weighted_outdegree = Node.ref("node"), Float.ref("node_weighted_outdegree")
weighted_outdegree = graph.weighted_outdegree()
model.select(node.id, node_weighted_outdegree).where(
    weighted_outdegree(node, node_weighted_outdegree)
).inspect()
#     id  node_weighted_outdegree
# 0   1                      1.0
# 1   2                      1.0
# 2   3                      0.0

# 4. Use 'of' parameter to constrain the set of nodes to compute weighted outdegree of
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 2)).define(subset(node))
constrained_weighted_outdegree = graph.weighted_outdegree(of=subset)
model.select(node.id, node_weighted_outdegree).where(
    constrained_weighted_outdegree(node, node_weighted_outdegree)
).inspect()
#     id  node_weighted_outdegree
# 0   1                      1.0
# 1   2                      1.0
```

**Notes:**

The relationship returned by `weighted_outdegree(...)` is cached for a given set of arguments.
All `weighted_outdegree(...)` calls with the same arguments will return the same relationship.

The `weighted_outdegree()` method, called with no parameters, computes
the full weighted outdegree relationship. In contrast, `weighted_outdegree(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the weighted outdegree relation is needed
across a program, `weighted_outdegree()` is typically more efficient; this is the
typical case. Use `weighted_outdegree(of=subset)` only when small subsets of the
weighted outdegree relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`degree_centrality`()

```python
Graph.degree_centrality(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

The calculation uses the node's weighted degree.

Returns a binary relationship containing the degree centrality of each node.

Degree centrality is a measure of a node's importance, defined as its
degree (or weighted degree for weighted graphs) divided by the number
of other nodes in the graph.

For unweighted graphs without self-loops, this value will be at most 1.0;
unweighted graphs with self-loops might have nodes with a degree centrality
greater than 1.0. Weighted graphs may have degree centralities
greater than 1.0 as well.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the degree centrality computation: only degree centralities of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  degree centrality.

**Relationship Schema:**

`degree_centrality(node, centrality)`

- **node** (*Node*): The node.
- **centrality** (*Float*): The degree centrality of the node.

**Examples:**

**Unweighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an unweighted graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the degree centrality of each node and inspect
node, centrality = Node.ref("node"), Float.ref("centrality")
degree_centrality = graph.degree_centrality()
model.select(node.id, centrality).where(degree_centrality(node, centrality)).inspect()
#    id centrality
# 0   1   0.333333
# 1   2   1.000000
# 2   3   1.000000
# 3   4   0.333333
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute degree centrality of
# Define a subset containing only nodes 2 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 2, node.id == 3)).define(subset(node))

# Get degree centralities only of nodes in the subset
constrained_degree_centrality = graph.degree_centrality(of=subset)
model.select(node.id, centrality).where(
    constrained_degree_centrality(node, centrality)
).inspect()
#     id centrality
# 0   2        1.0
# 1   3        1.0
```

**Weighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a weighted graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2, weight=2.0),
    Edge.new(src=n1, dst=n3, weight=0.5),
    Edge.new(src=n2, dst=n3, weight=1.5),
)

# 3. Select the degree centrality using weighted degrees
node, centrality = Node.ref("node"), Float.ref("centrality")
degree_centrality = graph.degree_centrality()
model.select(node.id, centrality).where(degree_centrality(node, centrality)).inspect()
#     id  centrality
# 0   1        1.25
# 1   2        1.75
# 2   3        1.00
```

**Notes:**

The relationship returned by `degree_centrality(...)` is cached for a given set of arguments.
All `degree_centrality(...)` calls with the same arguments will return the same relationship.

The `degree_centrality()` method, called with no parameters, computes
the full degree centrality relationship. In contrast, `degree_centrality(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the degree centrality relation is needed
across a program, `degree_centrality()` is typically more efficient; this is the
typical case. Use `degree_centrality(of=subset)` only when small subsets of the
degree centrality relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`eigenvector_centrality`()

```python
Graph.eigenvector_centrality(
    tolerance: float = 1e-06, max_iter: int = 200, *, diagnostic_info: bool = False
) -> Union[Relationship, Tuple[Relationship, Relationship]]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

See Notes for convergence criteria.

Directed

✘

Will not converge.

Weighted

✔

Assumes non-negative weights.

Returns a binary relationship containing the eigenvector centrality of each node.

**Parameters:**

- `tolerance` (`float`, default: `1e-06`) - The convergence tolerance for the eigenvector centrality calculation. Must be a non-negative float. Default is 1e-6.
- `max_iter` (`int`, default: `200`) - The maximum number of iterations to perform in the power method. Default is 200.
- `diagnostic_info` (`bool`, default: `False`) - If `True`, returns diagnostic information alongside centrality scores. If `False` (default), returns only centrality scores.

**Returns:**

- `Relationship or tuple of Relationships` - If `diagnostic_info` is `False` (default), returns a binary
  relationship where each tuple represents a node and its
  eigenvector centrality.

  If `diagnostic_info` is `True`, returns a tuple of
  `(eigenvector_centrality, diagnostic_info)` where:

  - `eigenvector_centrality` is the binary relationship described above
  - `diagnostic_info` is a binary relationship where each tuple
    contains a diagnostic name string and diagnostic value string.

**Raises:**

- `DirectedGraphNotSupported` - If the graph is directed.

**Relationship Schema:**

When `diagnostic_info=False` (default):

`eigenvector_centrality(node, centrality)`

- **node** (*Node*): The node.
- **centrality** (*Float*): The eigenvector centrality of the node.

When `diagnostic_info=True`, returns two relationships:

- `eigenvector_centrality(node, centrality)` as described above; and
- `diagnostic_info(diagnostic_name, diagnostic_value)`
- **diagnostic\_name** (*String*): The name of the diagnostic information.
- **diagnostic\_value** (*String*): The value of the diagnostic information.

**Examples:**

**Unweighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an unweighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2), Edge.new(src=n2, dst=n3), Edge.new(src=n3, dst=n4)
)

# 3. Select the eigenvector centrality for each node and inspect
node, centrality = Node.ref("node"), Float.ref("centrality")
eigenvector_centrality = graph.eigenvector_centrality()
model.select(node.id, centrality).where(
    eigenvector_centrality(node, centrality)
).inspect()
#   id  centrality
# 0  1    0.371748
# 1  2    0.601501
# 2  3    0.601501
# 3  4    0.371748
```

**Weighted Graph Example**

```python
# 1. Set up a weighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2, weight=0.8),
    Edge.new(src=n2, dst=n3, weight=0.7),
    Edge.new(src=n3, dst=n3, weight=2.0),
    Edge.new(src=n2, dst=n4, weight=1.5),
)

# 3. Select the eigenvector centrality for each node and inspect
node, centrality = Node.ref("node"), Float.ref("centrality")
eigenvector_centrality = graph.eigenvector_centrality()
model.select(node.id, centrality).where(
    eigenvector_centrality(node, centrality)
).inspect()
#   id  centrality
# 0  1    0.157327
# 1  2    0.473250
# 2  3    0.815024
# 3  4    0.294988
```

**Diagnostic Information**

```python
# Repeat steps 1. and 2. from the previous example.
# 3. Get eigenvector centrality along with diagnostic information
eigenvector_centrality, diag_info = graph.eigenvector_centrality(diagnostic_info=True)
model.select(node.id, centrality).where(
    eigenvector_centrality(node, centrality)
).inspect()
#   id  centrality
# 0  1    0.157327
# 1  2    0.473250
# 2  3    0.815024
# 3  4    0.294988
model.select(diag_info[0], diag_info[1]).where(
    diag_info[0] == "Termination status"
).inspect()
#      diagnostic_name diagnostic_value
# 0 Termination status        Converged
```

**Notes:**

The relationship(s) returned by `eigenvector_centrality(...)` is (are) cached
for a given set of arguments. All `eigenvector_centrality(...)` calls with the
same arguments will return the same relationship(s).

Eigenvector centrality is a measure of the centrality or importance
of a node in a graph based on finding the eigenvector associated
with the top eigenvalue of the adjacency matrix. We use the [power
method](https://en.wikipedia.org/wiki/Power_iteration) to compute the
eigenvector in our implementation. Note that
the power method requires the adjacency matrix to be diagonalizable
and will only converge if the absolute value of the top 2
eigenvalues is distinct. Thus, if the graph you are using has an
adjacency matrix that is not diagonalizable or the top two
eigenvalues are not distinct, this method will not converge.
Specifically, bipartite graphs have symmetric spectra, so this computation
will not converge. In cases where eigenvector centrality does not converge,
consider PageRank.

In the case of weighted graphs, weights are assumed to be non-negative.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`betweenness_centrality`()

```python
Graph.betweenness_centrality(
    num_pivots: int = 100, *, diagnostic_info: bool = False
) -> Union[Relationship, Tuple[Relationship, Relationship]]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✘

Not supported by this implementation.

Returns a binary relationship containing the betweenness centrality of each node,
possibly in a tuple alongside another binary relationship containing diagnostic
information of the computation.

Betweenness centrality measures how important a node is based on how many times that
node appears in a shortest path between any two nodes in the graph. Nodes with high
betweenness centrality represent bridges between different parts of the graph. For
example, in a network representing airports and flights between them, nodes with high
betweenness centrality may identify "hub" airports that connect flights to different
regions.

**Parameters:**

- `num_pivots` (`int`, default: `100`) - The number of pivot nodes to sample as BFS/SSSP sources for approximating betweenness centrality. A larger value yields a more accurate approximation at the cost of increased runtime. When set to |V|, the algorithm reduces to the exact Brandes algorithm. Default is 100.
- `diagnostic_info` (`bool`, default: `False`) - If `True`, returns diagnostic information alongside centrality scores. If `False` (default), returns only centrality scores.

**Returns:**

- `Relationship or tuple of Relationships` - If `diagnostic_info` is `False` (default), returns a binary
  relationship where each tuple represents a node and its
  betweenness centrality.

  If `diagnostic_info` is `True`, returns a tuple of
  `(betweenness_centrality, diagnostic_info)` where:

  - `betweenness_centrality` is the binary relationship described above
  - `diagnostic_info` is a binary relationship where each tuple
    contains a diagnostic name string and diagnostic value string.

**Raises:**

- `NotImplementedError` - If the graph is weighted.

**Relationship Schema:**

`betweenness_centrality(node, centrality)`

- **node** (*Node*): The node.
- **centrality** (*Float*): The betweenness centrality of the node.

When `diagnostic_info=True`, returns two relationships:

- `betweenness_centrality(node, centrality)` as described above; and
- `diagnostic_info(diagnostic_name, diagnostic_value)`
- **diagnostic\_name** (*String*): The name of the diagnostic information.
- **diagnostic\_value** (*String*): The value of the diagnostic information.

**Examples:**

```python
from relationalai.semantics import Model, define, select, Float, String
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the betweenness centrality for each node and inspect
node, centrality = Node.ref("node"), Float.ref("centrality")
betweenness_centrality, diagnostic_info_rel = graph.betweenness_centrality(
    diagnostic_info=True
)
model.select(node.id, centrality).where(
    betweenness_centrality(node, centrality)
).inspect()
#   id  centrality
# 0  1         0.0
# 1  2         3.0
# 2  3         0.0
# 3  4         0.0

# 4. Inspect diagnostic info (filter one row at a time for stable output order)
key, value = String.ref("diagnostic_name"), String.ref("diagnostic_value")
model.select(key, value).where(
    diagnostic_info_rel(key, value), key == "Number of pivots used"
).inspect()
#          diagnostic_name diagnostic_value
# 0  Number of pivots used                4

model.select(key, value).where(
    diagnostic_info_rel(key, value), key == "Scaling factor"
).inspect()
#    diagnostic_name diagnostic_value
# 0   Scaling factor         1.000000

model.select(key, value).where(
    diagnostic_info_rel(key, value), key == "Maximum distance seen"
).inspect()
#          diagnostic_name diagnostic_value
# 0  Maximum distance seen                2
```

**Notes:**

The relationship(s) returned by `betweenness_centrality(...)` is (are) cached
for a given set of arguments. All `betweenness_centrality(...)` calls with the
same arguments will return the same relationship(s).

Calculating betweenness centrality involves computing all of the shortest paths between
every pair of nodes in a graph and can be expensive to calculate exactly. The
`betweenness_centrality` relation gives an approximation using the
[Brandes-Pich](https://www.worldscientific.com/doi/abs/10.1142/S0218127407018403)
algorithm, which samples "pivot nodes" uniformly at random and performs single-source
shortest-path computations from those nodes. The result is then rescaled using
the scaling factor `|V|/num_pivots`.

This implementation supports sampling-based approximation via the `num_pivots` parameter,
which controls the number of pivot nodes used in the computation. The default value of 100 pivots
yields a time complexity of O(100 \* (|V|+|E|)). When the number of pivots equals or exceeds the
graph size, the algorithm reduces to the exact
[Brandes algorithm](http://snap.stanford.edu/class/cs224w-readings/brandes01centrality.pdf),
with time complexity O(|V|(|V|+|E|)) for unweighted graphs.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`pagerank`()

```python
Graph.pagerank(
    damping_factor: float = 0.85,
    tolerance: float = 1e-06,
    max_iter: int = 200,
    *,
    diagnostic_info: bool = False
) -> Union[Relationship, Tuple[Relationship, Relationship]]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Assumes non-negative weights.

Unweighted

✔

Returns a binary relationship containing the PageRank score of each node.

**Parameters:**

- `damping_factor` (`float`, default: `0.85`) - The damping factor for the PageRank calculation. Must be in the range \[0, 1). Default is 0.85.
- `tolerance` (`float`, default: `1e-06`) - The convergence tolerance for the PageRank calculation. Must be a non-negative float. Default is 1e-6.
- `max_iter` (`int`, default: `200`) - The maximum number of iterations for PageRank to run. Must be a positive integer. Default is 200.
- `diagnostic_info` (`bool`, default: `False`) - If `True`, returns diagnostic information alongside PageRank scores. If `False` (default), returns only PageRank scores.

**Returns:**

- `Relationship or tuple of Relationships` - If `diagnostic_info` is `False` (default), returns a binary
  relationship where each tuple represents a node and its
  PageRank score.

  If `diagnostic_info` is `True`, returns a tuple of
  `(pagerank, diagnostic_info)` where:

  - `pagerank` is the binary relationship described above
  - `diagnostic_info` is a binary relationship where each tuple
    contains a diagnostic name string and diagnostic value string.

**Relationship Schema:**

When `diagnostic_info=False` (default):

`pagerank(node, score)`

- **node** (*Node*): The node.
- **score** (*Float*): The PageRank score of the node.

When `diagnostic_info=True`, returns two relationships:

- `pagerank(node, score)` as described above; and
- `diagnostic_info(diagnostic_name, diagnostic_value)`
- **diagnostic\_name** (*String*): The name of the diagnostic information.
- **diagnostic\_value** (*String*): The value of the diagnostic information.

**Examples:**

**Unweighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an unweighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Compute PageRank with default parameters and inspect
node, score = Node.ref("node"), Float.ref("score")
pagerank = graph.pagerank()
model.select(node.id, score).where(pagerank(node, score)).inspect()
#    id     score
# 0   1  0.155788
# 1   2  0.417488
# 2   3  0.270936
# 3   4  0.155788
```

**Weighted Graph Example with Configuration**

```python
# 1. Set up a weighted, directed graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n1, dst=n3, weight=2.0),
    Edge.new(src=n3, dst=n4, weight=3.0),
)

# 3. Compute PageRank with custom parameters and inspect
node, score = Node.ref("node"), Float.ref("score")
pagerank = graph.pagerank()
model.select(node.id, score).where(pagerank(node, score)).inspect()
#    id     score
# 0   1  0.264904
# 1   2  0.112556
# 2   3  0.387444
# 3   4  0.235096
```

**Directed Example with Diagnostics**

```python
# 1. Set up graph as above
model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n1, dst=n3, weight=2.0),
    Edge.new(src=n3, dst=n4, weight=3.0),
)

# 2. Compute PageRank and retrieve results and diagnostic info
node, score = Node.ref("node"), Float.ref("score")
pagerank, diagnostic_info = graph.pagerank(diagnostic_info=True)

# 3. Select the results
model.select(node.id, score).where(pagerank(node, score)).inspect()
#    id     score
# 0   1  0.161769
# 1   2  0.207603
# 2   3  0.253438
# 3   4  0.377190

# 4. Select termination status from diagnostic info
key, value = String.ref("diagnostic_name"), String.ref("diagnostic_value")
model.select(key, value).where(
    diagnostic_info(key, value), key == "Termination status"
).inspect()
#       diagnostic_name      diagnostic_value
# 0  Termination status             Converged

# 5. Select number of iterations from diagnostic info
model.select(key, value).where(
    diagnostic_info(key, value), key == "Iterations"
).inspect()
#       diagnostic_name      diagnostic_value
# 0          Iterations                    12
```

**Notes:**

The relationship(s) returned by `pagerank(...)` is (are) cached
for a given set of arguments. All `pagerank(...)` calls with the
same arguments will return the same relationship(s).

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`triangle`()

```python
Graph.triangle(*, full: Optional[bool] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a ternary relationship containing all triangles in the graph.

Unlike `unique_triangle`, this relationship contains all permutations
of the nodes for each triangle found.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes triangles for all triplets of nodes in the graph. This computation can be expensive for large graphs. Must be set to `True` to compute the full triangle relationship. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a triangle.

**Raises:**

- `ValueError` - If `full` is not provided.
  If `full` is not `True`.

**Relationship Schema:**

`triangle(node_a, node_b, node_c)`

- **node\_a** (*Node*): The first node in the triangle.
- **node\_b** (*Node*): The second node in the triangle.
- **node\_c** (*Node*): The third node in the triangle.

**Examples:**

**Directed Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph with a 3-cycle
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n1),
)

# 3. Select all triangles and inspect
a, b, c = Node.ref("a"), Node.ref("b"), Node.ref("c")
triangle = graph.triangle(full=True)
model.select(a.id, b.id, c.id).where(triangle(a, b, c)).inspect()
#    id  id_2  id_3
# 0   1     2     3
# 1   2     3     1
# 2   3     1     2
```

**Undirected Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph with a triangle
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define the same nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n1),
)

# 3. Select all triangles and inspect
a, b, c = Node.ref("a"), Node.ref("b"), Node.ref("c")
triangle = graph.triangle(full=True)
model.select(a.id, b.id, c.id).where(triangle(a, b, c)).inspect()
#    id  id_2  id_3
# 0   1     2     3
# 1   1     3     2
# 2   2     1     3
# 3   2     3     1
# 4   3     1     2
# 5   3     2     1
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`unique_triangle`()

```python
Graph.unique_triangle(*, full: Optional[bool] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a ternary relationship containing all unique triangles in the graph.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes unique triangles for all triplets of nodes in the graph. This computation can be expensive for large graphs. Must be set to `True` to compute the full unique\_triangle relationship. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a unique
  triangle.

**Raises:**

- `ValueError` - If `full` is not provided.
  If `full` is not `True`.

**Relationship Schema:**

`unique_triangle(node_a, node_b, node_c)`

- **node\_a** (*Node*): The first node in the triangle.
- **node\_b** (*Node*): The second node in the triangle.
- **node\_c** (*Node*): The third node in the triangle.

**Examples:**

**Directed Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n1),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n3, dst=n4),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the unique triangles and inspect
a, b, c = Node.ref("a"), Node.ref("b"), Node.ref("c")
unique_triangle = graph.unique_triangle(full=True)
model.select(a.id, b.id, c.id).where(unique_triangle(a, b, c)).inspect()
#   id id_2 id_3
# 0  2    1    3
```

**Undirected Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges forming two triangles
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n1),  # Forms triangle (1,2,3)
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n3, dst=n4),  # Forms triangle (2,3,4)
)

# 3. Select the unique triangles and inspect
a, b, c = Node.ref("a"), Node.ref("b"), Node.ref("c")
unique_triangle = graph.unique_triangle(full=True)
model.select(a.id, b.id, c.id).where(unique_triangle(a, b, c)).inspect()
#   id id_2 id_3
# 0  2    1    3
# 1  4    2    3
```

**Notes:**

This relationship contains triples of nodes `(a, b, c)` representing
unique triangles.

For **undirected graphs**, uniqueness of each triangle is guaranteed
because the relationship only contains triples where `a < b < c`.

For **directed graphs**, the triple `(a, b, c)` represents a triangle
with directed edges `(a, b)`, `(b, c)`, and `(c, a)`, and is unique up
to ordering of the nodes and direction of the edges. `unique_triangle`
only contains triples such that `a < b`, `a < c`, and `b != c`. For
example, the triples `(1, 2, 3)` and `(1, 3, 2)` represent two unique
directed triangles.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`num_triangles`()

```python
Graph.num_triangles() -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a unary relationship containing the total number of unique triangles in the graph.

This method counts the number of unique triangles as defined by the
`unique_triangle` relationship, which has different uniqueness
constraints for directed and undirected graphs.

**Returns:**

- `Relationship` - A unary relationship containing the total number of unique
  triangles in the graph.

**Relationship Schema:**

`num_triangles(count)`

- **count** (*Integer*): The total number of unique triangles in the graph.

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n1),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n3, dst=n4),
    Edge.new(src=n1, dst=n4),
)

# 3. Inspect the number of unique triangles
graph.num_triangles().inspect()
#   num_triangles
# 0             1
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`triangle_count`()

```python
Graph.triangle_count(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship containing the number of unique triangles each node belongs to.

A triangle is a set of three nodes where each node has a directed
or undirected edge to the other two nodes, forming a 3-cycle.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the triangle count computation: only triangle counts of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and the
  number of unique triangles it is a part of.

**Relationship Schema:**

`triangle_count(node, count)`

- **node** (*Node*): The node.
- **count** (*Integer*): The number of unique triangles the node belongs to.

**Examples:**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5 = [Node.new(id=i) for i in range(1, 6)]
model.define(n1, n2, n3, n4, n5)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n3, dst=n1),
    Edge.new(src=n3, dst=n4),
    Edge.new(src=n5, dst=n1),
)

# 3. Select the triangle count for each node and inspect
node, count = Node.ref("node"), Integer.ref("count")
triangle_count = graph.triangle_count()
model.select(node.id, count).where(triangle_count(node, count)).inspect()
#    id  count
# 0   1      1
# 1   2      1
# 2   3      1
# 3   4      0
# 4   5      0
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute triangle counts of
# Define a subset containing only nodes 1 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 3)).define(subset(node))

# Get triangle counts only of nodes in the subset
constrained_triangle_count = graph.triangle_count(of=subset)
model.select(node.id, count).where(constrained_triangle_count(node, count)).inspect()
#    id  count
# 0   1      1
# 1   3      1
```

**Notes:**

The relationship returned by `triangle_count(...)` is cached for a given set of arguments.
All `triangle_count(...)` calls with the same arguments will return the same relationship.

The `triangle_count()` method, called with no parameters, computes
the full triangle count relationship. In contrast, `triangle_count(of=subset)` computes a
constrained relationship specific to the passed-in `subset`.
When a significant fraction of the triangle count relation is needed
across a program, `triangle_count()` is typically more efficient; this is the
typical case. Use `triangle_count(of=subset)` only when small subsets of the
triangle count relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`local_clustering_coefficient`()

```python
Graph.local_clustering_coefficient(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✘

Undirected only.

Weighted

✔

Weights are ignored.

Returns a binary relationship containing the local clustering coefficient of each node.

The local clustering coefficient quantifies how close a node's neighbors
are to forming a clique (a complete subgraph). The coefficient ranges
from 0.0 to 1.0, where 0.0 indicates none of the neighbors have edges
directly connecting them, and 1.0 indicates all neighbors have edges
directly connecting them.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the local clustering coefficient computation: only coefficients of nodes in this relationship are computed and returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and its
  local clustering coefficient.

**Raises:**

- `NotImplementedError` - If the graph is directed.

**Relationship Schema:**

`local_clustering_coefficient(node, coefficient)`

- **node** (*Node*): The node.
- **coefficient** (*Float*): The local clustering coefficient of the node.

**Examples:**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5 = [Node.new(id=i) for i in range(1, 6)]
model.define(n1, n2, n3, n4, n5)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n4),
    Edge.new(src=n4, dst=n5),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n3, dst=n5),
)

# 3. Select the local clustering coefficient for each node
node, coeff = Node.ref("node"), Float.ref("coeff")
lcc = graph.local_clustering_coefficient()
model.select(node.id, coeff).where(lcc(node, coeff)).inspect()
#    id     coeff
# 0   1  1.000000
# 1   2  0.666667
# 2   3  0.500000
# 3   4  0.666667
# 4   5  1.000000
```

```python
# 4. Use 'of' parameter to constrain the set of nodes to compute local clustering coefficients of
# Define a subset containing only nodes 1 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 3)).define(subset(node))

# Get local clustering coefficients only of nodes in the subset
constrained_lcc = graph.local_clustering_coefficient(of=subset)
model.select(node.id, coeff).where(constrained_lcc(node, coeff)).inspect()
#    id     coeff
# 0   1  1.0
# 1   3  0.5
```

**Notes:**

The local clustering coefficient for node `v` is:

```
(2 * num_neighbor_edges(v)) / (ext_degree(v) * (ext_degree(v) - 1))
```

where `num_neighbor_edges(v)` is the number of edges between
the neighbors of node `v`, and `ext_degree(v)` is the degree of the
node excluding self-loops. If `ext_degree(v)` is less than 2,
the local clustering coefficient is 0.0.

The relationship returned by `local_clustering_coefficient(...)` is cached for a given set of arguments.
All `local_clustering_coefficient(...)` calls with the same arguments will return the same relationship.

The `local_clustering_coefficient()` method, called with no parameters, computes
the full local clustering coefficient relationship. In contrast,
`local_clustering_coefficient(of=subset)` computes a constrained relationship
specific to the passed-in `subset`. When a significant fraction
of the local clustering coefficient relation is needed across a program,
`local_clustering_coefficient()` is typically more efficient; this is the typical
case. Use `local_clustering_coefficient(of=subset)` only when small subsets of the
local clustering coefficient relationship are needed collectively across the program.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`average_clustering_coefficient`()

```python
Graph.average_clustering_coefficient() -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✘

Undirected only.

Weighted

✔

Weights are ignored.

Returns a unary relationship containing the average clustering coefficient of the graph.

The average clustering coefficient is the average of the local
clustering coefficients of the nodes in a graph.

**Returns:**

- `Relationship` - A unary relationship containing the average clustering coefficient
  of the graph.

**Raises:**

- `NotImplementedError` - If the graph is directed.

**Relationship Schema:**

`average_clustering_coefficient(coefficient)`

- **coefficient** (*Float*): The average clustering coefficient of the graph.

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5 = [Node.new(id=i) for i in range(1, 6)]
model.define(n1, n2, n3, n4, n5)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n1, dst=n4),
    Edge.new(src=n1, dst=n5),
    Edge.new(src=n2, dst=n3),
)

# 3. Inspect the average clustering coefficient
graph.average_clustering_coefficient().inspect()
#    coefficient
# 0     0.433333
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`reachable`()

```python
Graph.reachable(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship of pairs of nodes (u, v) where v is reachable from u.

A node `v` is considered reachable from a node `u` if there is a path
of edges from `u` to `v`.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes reachability for all pairs of nodes in the graph. This computation can be expensive for large graphs. Must be set to `True` to compute the full reachable relationship. Cannot be used with other parameters.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the first position of the reachable computation: only reachability from nodes in this relationship are returned. Cannot be used with other parameters.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the second position of the reachable computation: only reachability to nodes in this relationship are returned. Cannot be used with other parameters.
- `between` (`Relationship`, default: `None`) - Not yet supported for reachable. If provided, raises an error. If you need this capability, please reach out.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and a
  node that is reachable from it.

**Relationship Schema:**

`reachable(from_node, to_node)`

- **from\_node** (*Node*): The node from which the path originates.
- **to\_node** (*Node*): The node that is reachable from the first node.

**Examples:**

**Directed Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n2),
)

# 3. Select all reachable pairs and inspect
from_node, to_node = Node.ref("start"), Node.ref("end")
reachable = graph.reachable(full=True)
model.select(from_node.id, to_node.id).where(reachable(from_node, to_node)).inspect()
#   id id_2
# 0  1    1
# 1  1    2
# 2  2    2
# 3  3    2
# 4  3    3
```

```python
# 4. Use 'from_' parameter to get reachability from specific nodes
# Define a subset containing nodes 1 and 3
subset = model.Relationship(f"{Node:node} is in from subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 3)).define(subset(node))

# Get reachability from nodes in the subset to all other nodes
reachable_from = graph.reachable(from_=subset)
model.select(from_node.id, to_node.id).where(
    reachable_from(from_node, to_node)
).inspect()
#   id id_2
# 0  1    1
# 1  1    2
# 2  3    2
# 3  3    3
```

```python
# 5. Use 'to' parameter to get reachability to specific nodes
# Define a different subset containing node 2
to_subset = model.Relationship(f"{Node:node} is in to subset")
node = Node.ref()
model.where(node.id == 2).define(to_subset(node))

# Get reachability from all nodes to node 2
reachable_to = graph.reachable(to=to_subset)
model.select(from_node.id, to_node.id).where(reachable_to(from_node, to_node)).inspect()
#   id id_2
# 0  1    2
# 1  2    2
# 2  3    2
```

**Undirected Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define the same nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n2),
)

# 3. Select all reachable pairs and inspect
from_node, to_node = Node.ref("start"), Node.ref("end")
reachable = graph.reachable(full=True)
model.select(from_node.id, to_node.id).where(reachable(from_node, to_node)).inspect()
#   id id_2
# 0  1    1
# 1  1    2
# 2  1    3
# 3  2    1
# 4  2    2
# 5  2    3
# 6  3    1
# 7  3    2
# 8  3    3
```

**Notes:**

The relationship returned by `reachable(...)` is cached for a given set of arguments.
All `reachable(...)` calls with the same arguments will return the same relationship.

The `reachable(full=True)` method computes the full reachable
relationship. In contrast, `reachable(from_=subset)` or
`reachable(to=subset)` compute constrained relationships. When a
significant fraction of the reachable relation is needed,
`reachable(full=True)` is typically more efficient. Use constrained
variants only when small subsets are needed.

In directed graphs, the `reachable` relationship is asymmetric: node B
may be reachable from node A without node A being reachable from node B. This
asymmetry means that `from_` and `to` parameters have distinct,
non-interchangeable meanings.

**Important:** Simultaneous use of `from_` and `to` parameters is not
yet supported. The `between` parameter is also not yet supported. If
you need these capabilities, please reach out.

There is a slight difference between `transitive closure` and
`reachable`. The transitive closure of a binary relation E is the
smallest relation that contains E and is transitive. When E is the
edge set of a graph, the transitive closure of E does not include
(u, u) if u is isolated. `reachable` is a different binary
relation in which any node u is always reachable from u. In
particular, `transitive closure` is a more general concept than
`reachable`.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`distance`()

```python
Graph.distance(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

The calculation uses edge weights.

Returns a ternary relationship containing
the shortest path length between pairs of nodes.

This method computes the shortest path length between all pairs of
reachable nodes. The calculation depends on whether the graph is
weighted:

- For **unweighted** graphs, the length is the number of edges in the
  shortest path.
- For **weighted** graphs, the length is the sum of edge weights
  along the shortest path. Edge weights are assumed to be non-negative.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes distances for all pairs of nodes in the graph. This computation can be expensive for large graphs. Must be set to `True` to compute the full distance relationship. Cannot be used with other parameters.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the first position (start\_node) of the distance computation: only distances from nodes in this relationship are returned. Cannot be used with other parameters.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the second position (end\_node) of the distance computation: only distances to nodes in this relationship are returned. Cannot be used with other parameters.
- `between` (`Relationship`, default: `None`) - Not yet supported for distance. If provided, raises an error. If you need this capability, please reach out.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a pair of nodes
  and the shortest path length between them.

**Relationship Schema:**

`distance(start_node, end_node, length)`

- **start\_node** (*Node*): The start node of the path.
- **end\_node** (*Node*): The end node of the path.
- **length** (*Integer* or *Float*): The shortest path length, returned
  as an Integer for unweighted graphs and a Float for weighted graphs.

**Examples:**

**Unweighted Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an unweighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
)

# 3. Select the shortest path length between all pairs of nodes
start, end = Node.ref("start"), Node.ref("end")
length = Integer.ref("length")
dist = graph.distance(full=True)
model.select(start.id, end.id, length).where(dist(start, end, length)).inspect()
#    id id_2 length
# 0   1    1      0
# 1   1    2      1
# 2   1    3      2
# 3   1    4      2
# 4   2    1      1
# 5   2    2      0
# 6   2    3      1
# 7   2    4      1
# 8   3    1      2
# 9   3    2      1
# 10  3    3      0
# 11  3    4      2
# 12  4    1      2
# 13  4    2      1
# 14  4    3      2
# 15  4    4      0
```

```python
# 4. Use 'from_' parameter to get distances from specific nodes
# Define a subset containing nodes 1 and 3
subset = model.Relationship(f"{Node:node} is in from subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 3)).define(subset(node))

# Get distances from nodes in the subset to all other nodes
dist_from = graph.distance(from_=subset)
model.select(start.id, end.id, length).where(dist_from(start, end, length)).inspect()
#   id id_2 length
# 0  1    1      0
# 1  1    2      1
# 2  1    3      2
# 3  1    4      2
# 4  3    1      2
# 5  3    2      1
# 6  3    3      0
# 7  3    4      2
```

```python
# 5. Use 'to' parameter to get distances to specific nodes
# Define a different subset containing node 4
to_subset = model.Relationship(f"{Node:node} is in to subset")
node = Node.ref()
model.where(node.id == 4).define(to_subset(node))

# Get distances from all nodes to node 4
dist_to = graph.distance(to=to_subset)
model.select(start.id, end.id, length).where(dist_to(start, end, length)).inspect()
#   id id_2 length
# 0  1    4      2
# 1  2    4      1
# 2  3    4      2
# 3  4    4      0
```

**Weighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a weighted, directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2, weight=2.0),
    Edge.new(src=n1, dst=n3, weight=0.5),
    Edge.new(src=n2, dst=n1, weight=1.5),
)

# 3. Select the shortest path length between all pairs of nodes
start, end = Node.ref("start"), Node.ref("end")
length = Float.ref("length")
dist = graph.distance(full=True)
model.select(start.id, end.id, length).where(dist(start, end, length)).inspect()
#   id id_2 length
# 0  1    1    0.0
# 1  1    2    2.0
# 2  1    3    0.5
# 3  2    1    1.5
# 4  2    2    0.0
# 5  2    3    2.0
# 6  3    3    0.0
```

**Notes:**

The relationship returned by `distance(...)` is cached for a given set of arguments.
All `distance(...)` calls with the same arguments will return the same relationship.

The `distance(full=True)` method computes the full distance
relationship. In contrast, `distance(from_=subset)` or
`distance(to=subset)` compute constrained relationships. When a
significant fraction of the distance relation is needed, `distance(full=True)`
is typically more efficient. Use constrained variants only when small
subsets are needed.

In directed graphs, the `distance` relationship is asymmetric: the
distance from node A to node B may differ from the distance from node B
to node A. This asymmetry means that `from_` and `to` parameters
have distinct, non-interchangeable meanings.

**Important:** Simultaneous use of `from_` and `to` parameters is not
yet supported. The `between` parameter is also not yet supported. If
you need these capabilities, please reach out.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`weakly_connected_component`()

```python
Graph.weakly_connected_component(*, of: Optional[Relationship] = None) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a binary relationship that maps each node to its weakly connected component.

A weakly connected component is a subgraph where for every pair of
nodes, there is a path between them in the underlying undirected graph.
For undirected graphs, this is equivalent to finding the connected
components.

**Parameters:**

- `of` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the weakly connected component computation: only component memberships of nodes in this relationship are returned.

**Returns:**

- `Relationship` - A binary relationship where each tuple represents a node and the
  identifier of the component it belongs to.

**Relationship Schema:**

`weakly_connected_component(node, component_id)`

- **node** (*Node*): The node.
- **component\_id** (*Node*): The identifier for the component.

**Examples:**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n2),
)

# 3. Select the component ID for each node and inspect
node, component_id = Node.ref("node"), Node.ref("component_id")
wcc = graph.weakly_connected_component()
model.select(node.id, component_id.id).where(wcc(node, component_id)).inspect()
#   id id_2
# 0  1    2
# 1  2    2
# 2  3    2
```

```python
# 4. Use 'of' parameter to constrain computation to subset of nodes
# Define a subset containing only nodes 1 and 3
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(model.union(node.id == 1, node.id == 3)).define(subset(node))

# Get component membership only for nodes in the subset
constrained_wcc = graph.weakly_connected_component(of=subset)
model.select(node.id, component_id.id).where(
    constrained_wcc(node, component_id)
).inspect()
#   id id_2
# 0  1    2
# 1  3    2
```

**Notes:**

The `component_id` is the node with the minimum ID within each
component.

The relationship returned by `weakly_connected_component(...)` is cached for a given set of arguments.
All `weakly_connected_component(...)` calls with the same arguments will return the same relationship.

The `weakly_connected_component()` method, called with no parameters,
computes the full weakly connected component relationship.

In contrast, `weakly_connected_component(of=subset)` computes a constrained
relationship specific to the passed-in `subset`.

Note that the constrained computation requires working over all nodes
in the components containing the nodes in `subset`. When that set
of nodes constitutes an appreciable fraction of the graph, the constrained
computation may be less efficient than computing the full relationship.
Use `weakly_connected_component(of=subset)` only when small subsets of
the weakly connected component relationship are needed collectively
across the program, and the associated components cover only a small
part of the graph.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`diameter_range`()

```python
Graph.diameter_range() -> Tuple[Relationship, Relationship]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✘

Weighted

✘

Estimates the graph diameter and returns it as a minimum and maximum bound.

**Returns:**

- `(Relationship, Relationship)` - A tuple containing two unary `Relationship` objects:
  (`min_bound`, `max_bound`).

  - `min_bound`: A relationship of the form `min_bound(value)`
    where `value` (*Integer*) is the lower bound of the
    estimated diameter.
  - `max_bound`: A relationship of the form `max_bound(value)`
    where `value` (*Integer*) is the upper bound of the
    estimated diameter.

**Relationship Schema:**

`min_bound(value)`

- **value** (*Integer*): The lower bound of the estimated diameter.

`max_bound(value)`

- **value** (*Integer*): The upper bound of the estimated diameter.

**Examples:**

**Connected Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a connected, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n4, dst=n3),
)

# 3. Get the diameter range and inspect each bound
min_bound, max_bound = graph.diameter_range()
min_bound.inspect()
#    value
# 0    3
max_bound.inspect()
#    value
# 0    4
```

**Disconnected Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a disconnected, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5 = [Node.new(id=i) for i in range(1, 6)]
model.define(n1, n2, n3, n4, n5)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n4),
    Edge.new(src=n4, dst=n5),
)

# 3. The range reflects the largest component {3, 4, 5}
min_bound, max_bound = graph.diameter_range()
min_bound.inspect()
#    value
# 0    2
max_bound.inspect()
#    value
# 0    2
```

**Notes:**

This method is used to determine the range of possible diameter
values in the graph. This is done by selecting a number of random
nodes in the graph and taking the maximum of all shortest paths
lengths to the rest of the graph. This gives a range per node.
Then, the intersection of these ranges is taken and the final range
is returned.

For disconnected graphs, `diameter_range` returns the diameter range
of the largest (weakly) connected component. This behavior deviates
from many graph theory resources, which typically define the diameter
of a disconnected graph as infinity.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`is_connected`()

```python
Graph.is_connected() -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Weights are ignored.

Returns a unary relationship containing whether the graph is connected.

A graph is considered connected if every node is reachable from every
other node in the underlying undirected graph.

**Returns:**

- `Relationship` - A unary relationship containing a boolean indicator of whether the graph
  is connected.

**Relationship Schema:**

`is_connected(connected)`

- **connected** (*Boolean*): Whether the graph is connected.

**Examples:**

**Connected Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a connected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n4, dst=n3),
)

# 3. Select and inspect the relation
model.select(graph.is_connected()).inspect()
#    is_connected
# 0          True
```

**Disconnected Graph Example**

```python
from relationalai.semantics import Model, define, select
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a disconnected graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5 = [Node.new(id=i) for i in range(1, 6)]
model.define(n1, n2, n3, n4, n5)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n4, dst=n5),  # This edge creates a separate component
)

# 3. Select and inspect the relation
model.select(graph.is_connected()).inspect()
#    is_connected
# 0         False
```

**Notes:**

An empty graph is considered connected.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`is_acyclic`()

```python
Graph.is_acyclic() -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✘

Not yet supported.

Directed

✔

Weighted

✔

Weights are ignored.

Returns a unary relationship containing whether the graph is acyclic.

A directed graph is acyclic if it contains no directed cycles.
This is determined using Kahn's topological sort algorithm: nodes with
indegree 0 are iteratively removed (peeled). If all nodes are
successfully removed, the graph is acyclic; otherwise, the remaining
nodes contain at least one cycle.

**Returns:**

- `Relationship` - A unary relationship containing a boolean indicator of whether the
  graph is acyclic.

**Raises:**

- `UndirectedGraphNotSupported` - If the graph is undirected. Please contact us if you need support
  for this feature.

**Relationship Schema:**

`is_acyclic(acyclic)`

- **acyclic** (*Boolean*): Whether the graph is acyclic.

**Examples:**

**Acyclic Graph (DAG) Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed acyclic graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
)

# 3. Select and inspect the relation
model.select(graph.is_acyclic()).inspect()
#    is_acyclic
# 0        True
```

**Cyclic Graph Example**

```python
from relationalai.semantics import Model
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph with a cycle
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges (1 -> 2 -> 3 -> 1)
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n1),
)

# 3. Select and inspect the relation
model.select(graph.is_acyclic()).inspect()
#    is_acyclic
# 0       False
```

**Notes:**

An empty graph and a graph with no edges are considered acyclic.
A self-loop is considered a cycle.

The implementation follows Kahn's topological sort algorithm, which
has theoretical asymptotic complexity O(|V| + |E|). In practice,
runtime scaling may be more complex. Please contact us if you have
specific performance questions or needs.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Path reasoning](/build/reasoning/path/index.md)1) [Use path results](/build/reasoning/path/use-path-results/index.md)1. [Keep path queries fast](/build/reasoning/path/use-path-results/index.md#keep-path-queries-fast)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`jaccard_similarity`()

```python
Graph.jaccard_similarity(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Unweighted

✔

Each edge weight is taken to be 1.0.

Returns a ternary relationship containing
the Jaccard similarity for pairs of nodes.

The Jaccard similarity is a measure between two nodes that ranges from
0.0 to 1.0, where higher values indicate greater similarity.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes the Jaccard similarity for all pairs of nodes in the graph. This computation can be expensive for large graphs, as the result can scale quadratically in the number of nodes. Mutually exclusive with other parameters. Default is `None`.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the Jaccard similarity computation: only Jaccard similarity scores for node pairs where the first node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. Can only be used together with the `from_` parameter. When provided with `from_`, constrains the domain of the Jaccard similarity computation: only Jaccard similarity scores for node pairs where the first node is in `from_` and the second node is in `to` are computed and returned. Default is `None`.
- `between` (`Relationship`, default: `None`) - A binary relationship containing pairs of nodes. When provided, constrains the domain of the Jaccard similarity computation: only Jaccard similarity scores for the specific node pairs in this relationship are computed and returned. Mutually exclusive with other parameters. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a pair of nodes
  and their Jaccard similarity.

**Raises:**

- `TypeError` - If `from_`, `to`, or `between` is not a `Relationship`.
- `ValueError` - If `full` is provided with any other parameter.
  If `between` is provided with any other parameter.
  If `from_` is provided with any parameter other than `to`.
  If `to` is provided without the `from_` parameter.
  If none of `full`, `from_`, or `between` is provided.
  If `full` is not `True` or `None`.
  If `from_`, `to`, or `between` is not attached to the same model as the graph.
  If `from_`, `to`, or `between` does not contain the graph's `Node` concept.
  If `from_` or `to` is not a unary relationship.
  If `between` is not a binary relationship.

**Relationship Schema:**

`jaccard_similarity(node_u, node_v, score)`

- **node\_u** (*Node*): The first node in the pair.
- **node\_v** (*Node*): The second node in the pair.
- **score** (*Float*): The Jaccard similarity of the pair.

**Examples:**

**Unweighted Graph Examples**

*Undirected Graph*

```python
from relationalai.semantics import Model, define, select, Float
from relationalai.semantics.reasoners.graph import Graph

model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
jaccard_similarity = graph.jaccard_similarity(full=True)
model.select(score).where(
    jaccard_similarity(u, v, score), u.id == 2, v.id == 4
).inspect()
#   score
# 0  0.25
```

*Directed Graph*

```python
from relationalai.semantics import Model, define, select, Float
from relationalai.semantics.reasoners.graph import Graph

model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n1),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n4, dst=n2),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
jaccard_similarity = graph.jaccard_similarity(full=True)
model.select(u.id, v.id, score).where(
    jaccard_similarity(u, v, score), u.id == 1
).inspect()
#   id id_2     score
# 0  1    1  1.000000
# 1  1    2  0.666667
```

**Weighted Graph Example**

*Undirected Graph*

```python
from relationalai.semantics import Model, define, select, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a weighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.6),
    Edge.new(src=n1, dst=n3, weight=1.4),
    Edge.new(src=n2, dst=n3, weight=0.46),
    Edge.new(src=n3, dst=n4, weight=2.5),
)

# 3. Select the weighted Jaccard similarity for the pair (1, 2)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
jaccard_similarity = graph.jaccard_similarity(full=True)
model.select(score).where(
    jaccard_similarity(u, v, score), u.id == 1, v.id == 2
).inspect()
#   score
# 0   0.1
```

*Directed Graph*

```python
from relationalai.semantics import Model, define, select, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a weighted, directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges with weights
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n3, weight=1.0),
    Edge.new(src=n2, dst=n3, weight=2.0),
    Edge.new(src=n3, dst=n1, weight=0.5),
    Edge.new(src=n3, dst=n2, weight=0.6),
    Edge.new(src=n4, dst=n2, weight=0.7),
)

# 3. Select the weighted Jaccard similarity for the pair (1, 2)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
jaccard_similarity = graph.jaccard_similarity(full=True)
model.select(u.id, v.id, score).where(
    jaccard_similarity(u, v, score), u.id == 1
).inspect()
#   id id_2     score
# 0  1    1  1.000000
# 1  1    2  0.454545
```

**Domain Constraint Examples**

```python
from relationalai.semantics import where

model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(node.id == 2).define(subset(node))

# Get Jaccard similarity scores only for pairs where first node is in subset
# Use 'from_' parameter to constrain the set of nodes for the first position
# Using the same undirected unweighted graph from above
constrained_jaccard_similarity = graph.jaccard_similarity(from_=subset)
model.select(u.id, v.id, score).where(
    constrained_jaccard_similarity(u, v, score)
).inspect()
#   id id_2 score
# 0  2    2  1.00
# 1  2    3  0.50
# 2  2    4  0.25
```

```python
# Use both 'from_' and 'to' parameters to constrain both positions
from_subset = model.Relationship(f"{Node:node} is in from_subset")
to_subset = model.Relationship(f"{Node:node} is in to_subset")
model.where(node.id == 2).define(from_subset(node))
model.where(node.id == 4).define(to_subset(node))

# Get Jaccard similarity scores only where first node is in from_subset and second node is in to_subset
constrained_jaccard_similarity = graph.jaccard_similarity(
    from_=from_subset, to=to_subset
)
model.select(u.id, v.id, score).where(
    constrained_jaccard_similarity(u, v, score)
).inspect()
#   id id_2 score
# 0  2    4  0.25
```

```python
# Use 'between' parameter to constrain to specific pairs of nodes
pairs = model.Relationship(f"{Node:node_a} and {Node:node_b} are a pair")
node_a, node_b = Node.ref(), Node.ref()
model.where(node_a.id == 2, node_b.id == 4).define(pairs(node_a, node_b))
model.where(node_a.id == 3, node_b.id == 4).define(pairs(node_a, node_b))

# Get Jaccard similarity scores only for the specific pairs (2, 4) and (3, 4)
constrained_jaccard_similarity = graph.jaccard_similarity(between=pairs)
model.select(u.id, v.id, score).where(
    constrained_jaccard_similarity(u, v, score)
).inspect()
#   id id_2    score
# 0  2    4 0.250000
# 1  3    4 0.666667
```

**Notes:**

The **unweighted undirected** Jaccard similarity between two nodes is
the ratio of: 1) the size of the intersection of their neighbors; to 2) the size
of the union of their neighbors.

The **unweighted directed** case is analogous, but inneighbors and
outneighbors are considered separately. The result is then the ratio
between two quantities:

1. the size of the intersection of the outneighbors plus the size of
   the intersection of the inneighbors.
2. the size of the union of the outneighbors plus the size of the union
   of the inneighbors.

The **weighted undirected** Jaccard similarity considers the weights
of the edges. The definition used here is taken from the reference noted
below. For a given pair of nodes `u` and `v`, it is the ratio between two quantities:

1. **Numerator**: For every other node `w` in the graph, find the
   minimum of the edge weights `(u, w)` and `(v, w)`, and sum these
   minimums.
2. **Denominator**: For every other node `w` in the graph, find the
   maximum of the edge weights `(u, w)` and `(v, w)`, and sum these
   maximums.

The **weighted directed** case is an extension of both the weighted undirected
and unweighted directed cases. For a given ordered pair of nodes `(u, v)`,
the result is (E1 + E2) / (E3 + E4), where the numbered expressions E1-E4
are defined as below, with the weight of non-existent edges taken to be 0.0:

E1.  For every other node `w` in the graph, find the minimum of
the edge weights `(u, w)` and `(v, w)`, and sum these minimums.
(This is a form of weighted intersection of out-neighbors.)
E2.  For every other node `w` in the graph, find the minimum of
the edge weights `(w, u)` and `(w, v)`, and sum these minimums.
(This is a form of weighted intersection of in-neighbors.)
E3.  For every other node `w` in the graph, find the maximum of
the edge weights `(u, w)` and `(v, w)`, and sum these maximums.
(This is a form of weighted union of out-neighbors.)
E4.  For every other node `w` in the graph, find the maximum of
the edge weights `(w, u)` and `(w, v)`, and sum these maximums.
(This is a form of weighted union of in-neighbors.)

In the weighted cases, if an edge does not exist, its weight is considered
0.0. This can be better understood via the following calculation for the weighted
example below.

| node id | edge weights to node 1 | edge weights to node 2 | min  | max |
| :------ | :--------------------- | :--------------------- | :--- | :-- |
| 1       | 0.0                    | 1.6                    | 0.0  | 1.6 |
| 2       | 1.6                    | 0.0                    | 0.0  | 1.6 |
| 3       | 1.4                    | 0.46                   | 0.46 | 1.4 |
| 4       | 0.0                    | 0.0                    | 0.0  | 0.0 |

The weighted Jaccard similarity between node 1 and 2 is then:
`0.46 / (1.6 + 1.6 + 1.4) = 0.1`.

Edge weights are assumed to be non-negative, so the neighborhood
vectors contain only non-negative elements. Therefore, when the
denominator is non-zero, the Jaccard similarity score is always between
0.0 and 1.0 inclusive.

When all edge weights of one or both of the nodes in a given pair are zero,
the denominator in the expression above will be zero, and
the pair's Jaccard similarity score will be `NaN`.

Moreover, only structurally supported values appear in the result. For example,
consider a pair of nodes `u` and `v`. If `u` and `v` share no common neighbors, i.e.
their Jaccard similarity value is not structurally supported, their Jaccard similarity
does not exist and hence the pair does not appear in the result. If `u` and
`v` do share common neighbors, i.e., their Jaccard similarity value is structurally
supported (even if the relevant weights are zero), their Jaccard similarity tuple
(`u`, `v`, `x`) appears in the result, computed as described above.

The relationship returned by `jaccard_similarity(...)` is cached for a given set of arguments.
All `jaccard_similarity(...)` calls with the same arguments will return the same relationship.

The `jaccard_similarity(full=True)` method computes the full
Jaccard similarity relationship for all pairs of nodes. This can be
expensive as the result can contain O(|V|²) tuples.

Calling `jaccard_similarity()` without arguments raises a `ValueError`,
to ensure awareness and explicit acknowledgement (`full=True`) of this cost.

In contrast, `jaccard_similarity(from_=subset)` constrains the
computation to tuples with the first position in the passed-in
`subset`. When a significant fraction of the Jaccard similarity
relation is needed across a program,
`jaccard_similarity(full=True)` is typically more efficient. Use
`jaccard_similarity(from_=subset)` only when small subsets of the
Jaccard similarity relationship are needed collectively across the
program.

The `to` parameter can be used together with `from_` to further
constrain the computation: `jaccard_similarity(from_=subset_a, to=subset_b)`
computes Jaccard similarity scores only for node pairs where the first node is in
`subset_a` and the second node is in `subset_b`. (Since `jaccard_similarity`
is symmetric in its first two positions, using `to` without `from_` would
be functionally redundant, and is not allowed.)

The `between` parameter provides another way to constrain the computation.
Unlike `from_` and `to`, which allow you to independently constrain the first
and second positions in `jaccard_similarity` tuples to sets of nodes, `between`
allows you to constrain the first and second positions, jointly, to specific pairs
of nodes.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`cosine_similarity`()

```python
Graph.cosine_similarity(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Unweighted

✔

Each edge weight is taken to be 1.0.

Returns a ternary relationship containing
the cosine similarity for pairs of nodes.

The cosine similarity measures the similarity between two nodes based
on the angle between their neighborhood vectors. The score ranges from
0.0 to 1.0, inclusive, where 1.0 indicates identical sets of neighbors.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes the cosine similarity for all pairs of nodes in the graph. This computation can be expensive for large graphs, as the result can scale quadratically in the number of nodes. Mutually exclusive with other parameters. Default is `None`.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the cosine similarity computation: only cosine similarity scores for node pairs where the first node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. Can only be used together with the `from_` parameter. When provided with `from_`, constrains the domain of the cosine similarity computation: only cosine similarity scores for node pairs where the first node is in `from_` and the second node is in `to` are computed and returned. Default is `None`.
- `between` (`Relationship`, default: `None`) - A binary relationship containing pairs of nodes. When provided, constrains the domain of the cosine similarity computation: only cosine similarity scores for the specific node pairs in this relationship are computed and returned. Mutually exclusive with other parameters. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a pair of nodes
  and their cosine similarity.

**Raises:**

- `TypeError` - If `from_`, `to`, or `between` is not a `Relationship`.
- `ValueError` - If `full` is provided with any other parameter.
  If `between` is provided with any other parameter.
  If `from_` is provided with any parameter other than `to`.
  If `to` is provided without the `from_` parameter.
  If none of `full`, `from_`, or `between` is provided.
  If `full` is not `True` or `None`.
  If `from_`, `to`, or `between` is not attached to the same model as the graph.
  If `from_`, `to`, or `between` does not contain the graph's `Node` concept.
  If `from_` or `to` is not a unary relationship.
  If `between` is not a binary relationship.

**Relationship Schema:**

`cosine_similarity(node_u, node_v, score)`

- **node\_u** (*Node*): The first node in the pair.
- **node\_v** (*Node*): The second node in the pair.
- **score** (*Float*): The cosine similarity of the pair.

**Examples:**

**Unweighted Graph Examples**

*Undirected Graph*

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
cosine_similarity = graph.cosine_similarity(full=True)
model.select(score).where(
    cosine_similarity(u, v, score), u.id == 2, v.id == 4
).inspect()
#       score
# 0  0.408248
```

*Directed Graph*

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n1),
    Edge.new(src=n3, dst=n2),
    Edge.new(src=n4, dst=n2),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
cosine_similarity = graph.cosine_similarity(full=True)
model.select(u.id, v.id, score).where(
    cosine_similarity(u, v, score), u.id == 1
).inspect()
#     id id_2     score
# 0  1    1  1.000000
# 1  1    2  0.816497
```

**Weighted Graph Examples**

*Undirected Graph*

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4, n13, n14 = [Node.new(id=i) for i in [1, 2, 3, 4, 13, 14]]
model.define(n1, n2, n3, n4, n13, n14)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.6),
    Edge.new(src=n1, dst=n3, weight=1.4),
    Edge.new(src=n2, dst=n3, weight=1.2),
    Edge.new(src=n3, dst=n4, weight=2.5),
    Edge.new(src=n14, dst=n13, weight=1.0),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
cosine_similarity = graph.cosine_similarity(full=True)
model.select(score).where(
    cosine_similarity(u, v, score), u.id == 1, v.id == 2
).inspect()
#       score
# 0  0.395103
```

*Directed Graph*

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

model = Model("test_model")
graph = Graph(model, directed=True, weighted=True)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n3, weight=1.0),
    Edge.new(src=n2, dst=n3, weight=2.0),
    Edge.new(src=n3, dst=n1, weight=0.5),
    Edge.new(src=n3, dst=n2, weight=0.6),
    Edge.new(src=n4, dst=n2, weight=0.7),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
cosine_similarity = graph.cosine_similarity(full=True)
model.select(u.id, v.id, score).where(
    cosine_similarity(u, v, score), u.id == 1
).inspect()
#     id id_2     score
# 0  1    1  1.000000
# 1  1    2  0.934118
```

**Domain Constraint Examples**

```python
# Use 'from_' parameter to constrain the set of nodes for the first position
# Using the same undirected weighted graph from above
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3, n4, n13, n14 = [Node.new(id=i) for i in [1, 2, 3, 4, 13, 14]]
model.define(n1, n2, n3, n4, n13, n14)
model.define(
    Edge.new(src=n1, dst=n2, weight=1.6),
    Edge.new(src=n1, dst=n3, weight=1.4),
    Edge.new(src=n2, dst=n3, weight=1.2),
    Edge.new(src=n3, dst=n4, weight=2.5),
    Edge.new(src=n14, dst=n13, weight=1.0),
)
u, v, score = Node.ref("u"), Node.ref("v"), Float.ref("score")
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(node.id == 2).define(subset(node))

# Get cosine similarity scores only for pairs where first node is in subset
constrained_cosine_similarity = graph.cosine_similarity(from_=subset)
model.select(u.id, v.id, score).where(
    constrained_cosine_similarity(u, v, score)
).inspect()
#    id id_2     score
# 0   2    1  0.395103
# 1   2    2  1.000000
# 2   2    3  0.360541
# 3   2    4  0.600000
```

```python
# Use both 'from_' and 'to' parameters to constrain both positions
from_subset = model.Relationship(f"{Node:node} is in from_subset")
to_subset = model.Relationship(f"{Node:node} is in to_subset")
model.where(node.id == 2).define(from_subset(node))
model.where(node.id == 1).define(to_subset(node))

# Get cosine similarity scores only where first node is in from_subset and second node is in to_subset
constrained_cosine_similarity = graph.cosine_similarity(from_=from_subset, to=to_subset)
model.select(u.id, v.id, score).where(
    constrained_cosine_similarity(u, v, score)
).inspect()
#    id id_2     score
# 0   2    1  0.395103
```

```python
# Use 'between' parameter to constrain to specific pairs of nodes
pairs = model.Relationship(f"{Node:node_a} and {Node:node_b} are a pair")
node_a, node_b = Node.ref(), Node.ref()
model.where(node_a.id == 1, node_b.id == 2).define(pairs(node_a, node_b))
model.where(node_a.id == 1, node_b.id == 1).define(pairs(node_a, node_b))

# Get cosine similarity scores only for the specific pairs (2, 4) and (3, 4)
constrained_cosine_similarity = graph.cosine_similarity(between=pairs)
model.select(u.id, v.id, score).where(
    constrained_cosine_similarity(u, v, score)
).inspect()
#    id id_2     score
# 0   1    1  1.000000
# 1   1    2  0.395103
```

**Notes:**

In linear algebra, the cosine of the angle between two vectors is given by their
Euclidean inner product (otherwise known as dot product) divided by the product
of their Euclidean norms.

Analogously, the cosine similarity of a pair of nodes in a graph is the cosine of
the angle between their (undirected or directed, weighted or unweighted)
neighborhood vectors.

This relationship uses the following definition for the neighborhood vectors:

- For **unweighted undirected** graphs, the vector for a node `u` contains a 1
  for each neighbor and a 0 for each non-neighbor.
- For **weighted undirected** graphs, the vector for a node `u` contains the
  edge weight for each neighbor and a 0 for each non-neighbor.
- For **unweighted directed** graphs, the vector for a node `u` is of length
  `2*|Nodes|`, and it contains:
  - in the first `|Nodes|` components, a 1 for each out-neighbor
    and a 0 for each non-out-neighbor.
  - in the remaining `|Nodes|` components, a 1 for each in-neighbor
    and a 0 for each non-in-neighbor.
- For **weighted directed** graphs, the vector for a node `u` is of length
  `2*|Nodes|`, and it contains:
  - in the first `|Nodes|` components, the edge weight for each out-neighbor
    and a 0 for each non-out-neighbor.
  - in the remaining `|Nodes|` components, the edge weight for each in-neighbor
    and a 0 for each non-in-neighbor.

Edge weights are assumed to be non-negative, so the neighborhood
vectors contain only non-negative elements. Therefore, when the
denominator is non-zero, the cosine similarity score is always between
0.0 and 1.0 inclusive.

When all the values in the neighbourhood vectors are zero,
the denominator in the expression above will be zero, and
the pair's cosine similarity score equals to `NaN`.
However, only structurally supported values are computed. For example,
consider a pair of nodes `u` and `v`. If `u` and `v` share no common neighbors, i.e.
their cosine similarity value is not structurally supported, their cosine similarity tuple
(`u`, `v`, `NaN`) is not computed and does not appear in the result. If `u` and
`v` do share common neighbors, i.e., their cosine similarity value is structurally
supported (even if the relevant weights are zero), their cosine similarity tuple
(`u`, `v`, `x`) appears in the result, computed as described above.

The relationship returned by `cosine_similarity(...)` is cached for a given set of arguments.
All `cosine_similarity(...)` calls with the same arguments will return the same relationship.

The `cosine_similarity(full=True)` method computes the full
cosine similarity relationship for all pairs of nodes. This can be
expensive as the result can contain O(|V|²) tuples.

Calling `cosine_similarity()` without arguments raises a `ValueError`,
to ensure awareness and explicit acknowledgement (`full=True`) of this cost.

In contrast, `cosine_similarity(from_=subset)` constrains the
computation to tuples with the first position in the passed-in
`subset`. When a significant fraction of the cosine similarity
relation is needed across a program,
`cosine_similarity(full=True)` is typically more efficient. Use
`cosine_similarity(from_=subset)` only when small subsets of the
cosine similarity relationship are needed collectively across the
program.

The `to` parameter can be used together with `from_` to further
constrain the computation: `cosine_similarity(from_=subset_a, to=subset_b)`
computes cosine similarity scores only for node pairs where the first node is in
`subset_a` and the second node is in `subset_b`. (Since `cosine_similarity`
is symmetric in its first two positions, using `to` without `from_` would
be functionally redundant, and is not allowed.)

The `between` parameter provides another way to constrain the computation.
Unlike `from_` and `to`, which allow you to independently constrain the first
and second positions in `cosine_similarity` tuples to sets of nodes, `between`
allows you constrain the first and second positions, jointly, to specific pairs
of nodes.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`adamic_adar`()

```python
Graph.adamic_adar(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Asymmetric; uses out/in neighbors.

Weighted

✔

Returns a ternary relationship containing the Adamic-Adar index for pairs of nodes.

The Adamic-Adar index is a similarity measure between two nodes based
on the amount of shared neighbors between them, giving more weight to
common neighbors that are less connected.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes the Adamic-Adar index for all pairs of nodes in the graph. This computation can be expensive for large graphs, as dependencies can scale quadratically in the number of edges or cubically in the number of nodes. Mutually exclusive with other parameters. Default is `None`.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the Adamic-Adar computation: only Adamic-Adar indices for node pairs where the first node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the Adamic-Adar computation: only Adamic-Adar indices for node pairs where the second node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `between` (`Relationship`, default: `None`) - A binary relationship containing pairs of nodes. When provided, constrains the domain of the Adamic-Adar computation: only Adamic-Adar indices for the specific node pairs in this relationship are computed and returned. Mutually exclusive with other parameters. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a pair of nodes
  and their Adamic-Adar index.

**Raises:**

- `TypeError` - If `from_`, `to`, or `between` is not a `Relationship`.
- `ValueError` - If `full` is provided with any other parameter.
  If `between` is provided with any other parameter.
  If `from_` is provided with any parameter other than `to`.
  If `to` is provided with any parameter other than `from_`.
  If none of `full`, `from_`, or `between` is provided.
  If `full` is not `True` or `None`.
  If `from_`, `to`, or `between` is not attached to the same model as the graph.
  If `from_`, `to`, or `between` does not contain the graph's `Node` concept.
  If `from_` or `to` is not a unary relationship.
  If `between` is not a binary relationship.

**Relationship Schema:**

`adamic_adar(node_u, node_v, score)`

- **node\_u** (*Node*): The first node in the pair.
- **node\_v** (*Node*): The second node in the pair.
- **score** (*Float*): The Adamic-Adar index of the pair.

**Examples:**

**Undirected Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)

# 3. Select the Adamic-Adar indices from the full relationship
u, v = Node.ref("u"), Node.ref("v")
score = Float.ref("score")
adamic_adar = graph.adamic_adar(full=True)
model.select(
    u.id,
    v.id,
    score,
).where(
    adamic_adar(u, v, score),
    u.id == 2,
    v.id == 4,
).inspect()
#   id id_2    score
# 0  2    4 0.910239
```

```python
# 4. Use 'from_' parameter to constrain the set of nodes for the first position
# Define a subset containing only node 1
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(node.id == 1).define(subset(node))

# Get Adamic-Adar indices only for pairs where first node is in subset
constrained_adamic_adar = graph.adamic_adar(from_=subset)
model.select(u.id, v.id, score).where(constrained_adamic_adar(u, v, score)).inspect()
#   id id_2    score
# 0  1    1 0.910239
# 1  1    3 0.910239
# 2  1    4 0.910239
```

```python
# 5. Use both 'from_' and 'to' parameters to constrain both positions
subset_a = model.Relationship(f"{Node:node} is in subset_a")
subset_b = model.Relationship(f"{Node:node} is in subset_b")
model.where(node.id == 1).define(subset_a(node))
model.where(node.id == 4).define(subset_b(node))

# Get Adamic-Adar indices only where first node is in subset_a and second node is in subset_b
constrained_adamic_adar = graph.adamic_adar(from_=subset_a, to=subset_b)
model.select(u.id, v.id, score).where(constrained_adamic_adar(u, v, score)).inspect()
#   id id_2    score
# 0  1    4 0.910239
```

```python
# 6. Use 'between' parameter to constrain to specific pairs of nodes
pairs = model.Relationship(f"{Node:node_a} and {Node:node_b} are a pair")
node_a, node_b = Node.ref(), Node.ref()
model.where(node_a.id == 1, node_b.id == 4).define(pairs(node_a, node_b))
model.where(node_a.id == 2, node_b.id == 3).define(pairs(node_a, node_b))

# Get Adamic-Adar indices only for the specific pairs (1, 4) and (2, 3)
constrained_adamic_adar = graph.adamic_adar(between=pairs)
model.select(u.id, v.id, score).where(constrained_adamic_adar(u, v, score)).inspect()
#   id id_2    score
# 0  1    4 0.910239
# 1  2    3 2.352934
```

**Directed Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge
n1, n2, n3 = [Node.new(id=i) for i in range(1, 4)]
model.define(n1, n2, n3)
model.define(
    Edge.new(src=n1, dst=n2), Edge.new(src=n2, dst=n3), Edge.new(src=n3, dst=n1)
)

# 2. Select the Adamic-Adar indices from the full relationship
u, v = Node.ref("u"), Node.ref("v")
score = Float.ref("score")
adamic_adar = graph.adamic_adar(full=True)
model.select(
    u.id,
    v.id,
    score,
).where(
    adamic_adar(u, v, score),
).inspect()
#   id id_2    score
# 0  1    3 1.442695
# 1  2    1 1.442695
# 2  3    2 1.442695
```

**Weighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a weighted undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge
n1, n2 = [Node.new(id=i) for i in range(1, 3)]
model.define(n1, n2)
model.define(Edge.new(src=n1, dst=n2, weight=1.5), Edge.new(src=n2, dst=n2, weight=0.1))

# 2. Select the Adamic-Adar index from the full relationship
u, v = Node.ref("u"), Node.ref("v")
score = Float.ref("score")
adamic_adar = graph.adamic_adar(full=True)
model.select(
    u.id,
    v.id,
    score,
).where(
    adamic_adar(u, v, score),
).inspect()
#   id id_2     score
# 0  1    1  3.020382
# 1  1    2  1.610871
# 2  2    1  1.610871
# 3  2    2  3.475429
```

**Notes:**

The Adamic-Adar index is defined in four variants depending on whether
the graph is directed and/or weighted.  Let Γ(u) denote the neighbors
of u, Γ\_out(u) the out-neighbors, and Γ\_in(u) the in-neighbors.

**Unweighted, undirected**:

```
AA(u,v) = Σ_{z ∈ Γ(u) ∩ Γ(v)}  1 / log(|Γ(z)|)
```

**Unweighted, directed** (common neighbor z must lie on the path u→z→v):

```
AA(u,v) = Σ_{z ∈ Γ_out(u) ∩ Γ_in(v)}  1 / log(|Γ(z)|)
```

**Weighted, undirected** (w(u,z) is the weight of edge u–z):

```
AA(u,v) = Σ_{z ∈ Γ(u) ∩ Γ(v)}  (w(u,z) + w(v,z)) / log(1 + weighted_degree(z))
```

**Weighted, directed** (w(u,z) is the weight of directed edge u→z):

```
AA(u,v) = Σ_{z ∈ Γ_out(u) ∩ Γ_in(v)}  (w(u,z) + w(z,v)) / log(1 + weighted_degree(z))
```

For unweighted graphs (both directed and undirected), self-loops on node z contribute
once to |Γ(z)|; while for weighted graphs (both directed and undirected), self-loops
on node z contribute twice to weighted\_degree(z).

The relationship returned by `adamic_adar(...)` is cached for a given set of arguments.
All `adamic_adar(...)` calls with the same arguments will return the same relationship.

The `adamic_adar(full=True)` method computes the full Adamic-Adar
relationship for all pairs of nodes. This can be expensive as
dependencies can contain O(|E|²) or O(|V|³) tuples depending on graph
density.

Calling `adamic_adar()` without arguments raises a `ValueError`,
to ensure awareness and explicit acknowledgement (`full=True`) of this cost.

In contrast, parameters `from_`, `to`, and `between` allow for
constraining the computation to specific subsets of the graph. When a
significant fraction of the Adamic-Adar relation is needed across a
program, `adamic_adar(full=True)` is typically more efficient. Use
parameters `from_`, `to`, and `between` only when small subsets of
the Adamic-Adar relationship are needed collectively across the
program.

`adamic_adar(from_=subset)` constrains the computation to
tuples with the first position in the passed-in `subset`.
`adamic_adar(to=subset)` constrains the computation to
tuples with the second position in the passed-in `subset`.
In directed graphs, the `adamic_adar` relationship is asymmetric:
the computation considers out-edges from `node_u` and in-edges to `node_v`.
This asymmetry means that `from_` and `to` parameters have distinct,
non-interchangeable meanings.

The `to` parameter can be used together with `from_` to further
constrain the computation: `adamic_adar(from_=subset_a, to=subset_b)`
computes Adamic-Adar indices only for node pairs where the first node is in
`subset_a` and the second node is in `subset_b`.

The `between` parameter provides another way to constrain the computation.
Unlike `from_` and `to`, which allow you to independently constrain the first
and second positions in `adamic_adar` tuples to sets of nodes, `between`
allows you constrain the first and second positions, jointly, to specific pairs
of nodes.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`preferential_attachment`()

```python
Graph.preferential_attachment(
    *,
    full: Optional[bool] = None,
    from_: Optional[Relationship] = None,
    to: Optional[Relationship] = None,
    between: Optional[Relationship] = None
) -> Relationship
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Returns a ternary relationship containing
the preferential attachment score for pairs of nodes.

The preferential attachment score between two nodes `u` and `v` is the
product of the outdegree of `u` and the indegree of `v` for directed unweighted
graphs, and the product of the degrees of `u` and `v` for undirected unweighted
graphs. In the case of weighted graphs, the weighted outdegrees, weighted indegrees, and
weighted degrees are used.

**Parameters:**

- `full` (`bool`, default: `None`) - If `True`, computes the preferential attachment score for all pairs of nodes in the graph. This computation can be expensive for large graphs, as the result can scale quadratically in the number of nodes. Mutually exclusive with other parameters. Default is `None`.
- `from_` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the preferential attachment computation: only preferential attachment scores for node pairs where the first node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `to` (`Relationship`, default: `None`) - A unary relationship containing a subset of the graph's nodes. When provided, constrains the domain of the preferential attachment computation: only preferential attachment scores for node pairs where the second node is in this relationship are computed and returned. Mutually exclusive with `full` and `between`. Default is `None`.
- `between` (`Relationship`, default: `None`) - A binary relationship containing pairs of nodes. When provided, constrains the domain of the preferential attachment computation: only preferential attachment scores for the specific node pairs in this relationship are computed and returned. Mutually exclusive with other parameters. Default is `None`.

**Returns:**

- `Relationship` - A ternary relationship where each tuple represents a pair of nodes
  and their preferential attachment score.

**Raises:**

- `TypeError` - If `from_`, `to`, or `between` is not a `Relationship`.
- `ValueError` - If `full` is provided with any other parameter.
  If `between` is provided with any other parameter.
  If `from_` is provided with any parameter other than `to`.
  If `to` is provided with any parameter other than `from_`.
  If none of `full`, `from_`, `to`, or `between` is provided.
  If `full` is not `True` or `None`.
  If `from_`, `to`, or `between` is not attached to the same model as the graph.
  If `from_`, `to`, or `between` does not contain the graph's `Node` concept.
  If `from_` or `to` is not a unary relationship.
  If `between` is not a binary relationship.

**Relationship Schema:**

`preferential_attachment(node_u, node_v, score)`

- **node\_u** (*Node*): The first node in the pair.
- **node\_v** (*Node*): The second node in the pair.
- **score** (*Integer* or *Float*): The preferential attachment score of the pair.
  For weighted graphs, this is a *Float*, for unweighted graphs it is an *Integer*.

**Examples:**

**Undirected Graph Example**

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)

# 3. Select the preferential attachment scores from the full relationship
u, v = Node.ref("u"), Node.ref("v")
score = Integer.ref("score")
preferential_attachment = graph.preferential_attachment(full=True)
model.select(
    u.id,
    v.id,
    score,
).where(
    preferential_attachment(u, v, score),
    u.id == 1,
    model.union(v.id == 2, v.id == 3),
).inspect()
#   id id_2 score
# 0  1    2     3
# 1  1    3     4
```

```python
# 4. Use 'from_' parameter to constrain the set of nodes for the first position
# Define a subset containing only node 1
from relationalai.semantics import where

subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(node.id == 1).define(subset(node))

# Get preferential attachment scores only for pairs where first node is in subset
constrained_preferential_attachment = graph.preferential_attachment(from_=subset)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    1     1
# 1  1    2     3
# 2  1    3     4
# 3  1    4     2
```

```python
# 5. Use 'to' parameter to constrain the set of nodes for the second position
# Get preferential attachment scores only for pairs where second node is in subset
constrained_preferential_attachment = graph.preferential_attachment(to=subset)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    1     1
# 1  2    1     3
# 2  3    1     4
# 3  4    1     2
```

```python
# 6. Use both 'from_' and 'to' parameters to constrain both positions
from_subset = model.Relationship(f"{Node:node} is in from_subset")
to_subset = model.Relationship(f"{Node:node} is in to_subset")
model.where(node.id == 1).define(from_subset(node))
model.where(node.id == 3).define(to_subset(node))

# Get preferential attachment scores only where first node is in from_subset and second node is in to_subset
constrained_preferential_attachment = graph.preferential_attachment(
    from_=from_subset, to=to_subset
)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    3     4
```

```python
# 7. Use 'between' parameter to constrain to specific pairs of nodes
pairs = model.Relationship(f"{Node:node_a} and {Node:node_b} are a pair")
node_a, node_b = Node.ref(), Node.ref()
model.where(node_a.id == 1, node_b.id == 3).define(pairs(node_a, node_b))
model.where(node_a.id == 2, node_b.id == 4).define(pairs(node_a, node_b))

# Get preferential attachment scores only for the specific pairs (1, 3) and (2, 4)
constrained_preferential_attachment = graph.preferential_attachment(between=pairs)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    3     4
# 1  2    4     6
```

**Directed Graph Example**

```python
from relationalai.semantics import Model, Integer, union
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a directed graph
model = Model("test_model")
graph = Graph(model, directed=True, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n2, dst=n3),
    Edge.new(src=n3, dst=n3),
    Edge.new(src=n2, dst=n4),
    Edge.new(src=n4, dst=n3),
)

# 3. Select the preferential attachment scores from the full relationship
u, v = Node.ref("u"), Node.ref("v")
score = Integer.ref("score")
preferential_attachment = graph.preferential_attachment(full=True)
model.select(
    u.id,
    v.id,
    score,
).where(
    preferential_attachment(u, v, score),
    u.id == 1,
    model.union(v.id == 2, v.id == 3),
).inspect()
#   id id_2 score
# 0  1    2     1
# 1  1    3     3
```

```python
# 4. Use 'from_' parameter to constrain the set of nodes for the first position
# Define a subset containing only node 1
subset = model.Relationship(f"{Node:node} is in subset")
node = Node.ref()
model.where(node.id == 1).define(subset(node))

# Get preferential attachment scores only for pairs where first node is in subset
constrained_preferential_attachment = graph.preferential_attachment(from_=subset)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    1     0
# 1  1    2     1
# 2  1    3     3
# 3  1    4     1
```

```python
# 5. Use 'to' parameter to constrain the set of nodes for the second position
# Get preferential attachment scores only for pairs where second node is in subset
constrained_preferential_attachment = graph.preferential_attachment(to=subset)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    1     0
# 1  2    1     0
# 2  3    1     0
# 3  4    1     0
```

```python
# 6. Use both 'from_' and 'to' parameters to constrain both positions
from_subset = model.Relationship(f"{Node:node} is in from_subset")
to_subset = model.Relationship(f"{Node:node} is in to_subset")
model.where(node.id == 1).define(from_subset(node))
model.where(node.id == 3).define(to_subset(node))

# Get preferential attachment scores only where first node is in from_subset and second node is in to_subset
constrained_preferential_attachment = graph.preferential_attachment(
    from_=from_subset, to=to_subset
)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    3     3
```

```python
# 7. Use 'between' parameter to constrain to specific pairs of nodes
pairs = model.Relationship(f"{Node:node_a} and {Node:node_b} are a pair")
node_a, node_b = Node.ref(), Node.ref()
model.where(node_a.id == 1, node_b.id == 3).define(pairs(node_a, node_b))
model.where(node_a.id == 2, node_b.id == 4).define(pairs(node_a, node_b))

# Get preferential attachment scores only for the specific pairs (1, 3) and (2, 4)
constrained_preferential_attachment = graph.preferential_attachment(between=pairs)
model.select(u.id, v.id, score).where(
    constrained_preferential_attachment(u, v, score)
).inspect()
#   id id_2 score
# 0  1    3     3
# 1  2    4     2
```

**Weighted Graph Example**

```python
from relationalai.semantics import Model, Float
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up a weighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and weighted edges
n1, n2, n3, n4 = [Node.new(id=i) for i in range(1, 5)]
model.define(n1, n2, n3, n4)
model.define(
    Edge.new(src=n1, dst=n2, weight=2.0),
    Edge.new(src=n1, dst=n3, weight=1.0),
    Edge.new(src=n2, dst=n3, weight=0.5),
    Edge.new(src=n3, dst=n4, weight=3.0),
)

# 3. Use 'from_' parameter to constrain the set of nodes for the first position
from_subset = model.Relationship(f"{Node:node} is in from_subset")
model.where(Node.id == 1).define(from_subset(Node))
score = Float.ref("score")

# Get preferential attachment scores only for pairs where first node is in subset
preferential_attachment = graph.preferential_attachment(from_=from_subset)
u, v = Node.ref("u"), Node.ref("v")
model.select(u.id, v.id, score).where(
    preferential_attachment(u, v, score),
).inspect()
#     id id_2 score
# 0  1    1    9.0
# 1  1    2    7.5
# 2  1    3   13.5
# 3  1    4    9.0
```

**Notes:**

The relationship returned by `preferential_attachment(...)` is cached for a given set of arguments.
All `preferential_attachment(...)` calls with the same arguments will return the same relationship.

The `preferential_attachment(full=True)` method computes the full
preferential attachment relationship for all pairs of nodes. This can be
expensive as the result contains O(|V|²) tuples.

Calling `preferential_attachment()` without arguments raises a `ValueError`,
to ensure awareness and explicit acknowledgement (`full=True`) of this cost.

In contrast, parameters `from_`, `to`, and `between` allow for
constraining the computation to specific subsets of the graph. When a
significant fraction of the preferential attachment relation is needed
across a program, `preferential_attachment(full=True)` is typically
more efficient. Use parameters `from_`, `to`, and `between` only
when small subsets of the preferential attachment relationship are
needed collectively across the program.

`preferential_attachment(from_=subset)` constrains the computation to
tuples with the first position in the passed-in `subset`.
`preferential_attachment(to=subset)` constrains the computation to
tuples with the second position in the passed-in `subset`.
In directed graphs, the `preferential_attachment` relationship is asymmetric:
the computation considers out-edges from `node_u` and in-edges to `node_v`.
This asymmetry means that `from_` and `to` parameters have distinct,
non-interchangeable meanings.

The `to` parameter can be used together with `from_` to further
constrain the computation: `preferential_attachment(from_=subset_a, to=subset_b)`
computes preferential attachment scores only for node pairs where the first node is in
`subset_a` and the second node is in `subset_b`.

The `between` parameter provides another way to constrain the computation.
Unlike `from_` and `to`, which allow you to independently constrain the first
and second positions in `preferential_attachment` tuples to sets of nodes, `between`
allows you constrain the first and second positions, jointly, to specific pairs
of nodes.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)

### .`infomap`()

```python
Graph.infomap(
    max_levels: int = 1,
    max_sweeps: int = 20,
    level_tolerance: float = 0.01,
    sweep_tolerance: float = 0.0001,
    teleportation_rate: float = 0.15,
    visit_rate_tolerance: float = 1e-15,
    randomization_seed: int = 8675309,
    *,
    diagnostic_info: bool = False
) -> Union[Relationship, Tuple[Relationship, Relationship]]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Only non-negative weights supported.

Unweighted

✔

Partitions nodes into communities using a variant of the Infomap algorithm.

This method maps nodes to community assignments based on the flow of
information on the graph.

**Parameters:**

- `max_levels` (`int`, default: `1`) - The maximum number of levels at which to optimize. Must be a positive integer. Default is 1.
- `max_sweeps` (`int`, default: `20`) - The maximum number of sweeps within each level. Must be a non-negative integer. Default is 20.
- `level_tolerance` (`float`, default: `0.01`) - Map equation progress threshold to continue to the next level. Must be a non-negative float. Default is 0.01.
- `sweep_tolerance` (`float`, default: `0.0001`) - Map equation progress threshold to continue to the next sweep. Must be a non-negative float. Default is 0.0001.
- `teleportation_rate` (`float`, default: `0.15`) - Teleportation rate for ergodic node visit rate calculation. Must be a float in \[1e-4, 1). Default is 0.15.
- `visit_rate_tolerance` (`float`, default: `1e-15`) - Convergence tolerance for ergodic node visit rate calculation. Must be a positive float. Default is 1e-15.
- `randomization_seed` (`int`, default: `8675309`) - The random number generator seed for the run. Must be a non-negative integer. Default is 8675309.
- `diagnostic_info` (`bool`, default: `False`) - If `True`, returns diagnostic information alongside community assignments. If `False` (default), returns only community assignments.

**Returns:**

- `Relationship or tuple of Relationships` - If `diagnostic_info` is `False` (default), returns a binary
  relationship where each tuple represents a node and its community
  assignment.

  If `diagnostic_info` is `True`, returns a tuple of
  `(community_assignments, diagnostic_info)` where:

  - `community_assignments` is the binary relationship described above
  - `diagnostic_info` is a binary relationship containing one tuple, whose
    second component is a diagnostic string describing the algorithm's
    convergence and termination behavior

**Relationship Schema:**

When `diagnostic_info=False` (default):

`infomap(node, community_label)`

- **node** (*Node*): The node.
- **community\_label** (*Integer*): The label of the community the node
  belongs to.

When `diagnostic_info=True`, returns two relationships:

- `infomap(node, community_label)` as described above; and
- `diagnostic_info(diagnostic_name, diagnostic_value)`
- **diagnostic\_name** (*String*): The name of the diagnostic information.
- **diagnostic\_value** (*String*): A diagnostic string describing the
  algorithm's convergence and termination behavior.

**Examples:**

**Unweighted Graph Example**

Compute community assignments for each node in an undirected graph. Here,
an undirected dumbbell graph resolves into two communities, namely its
two constituent three-cliques.

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges for a dumbbell graph
n1, n2, n3, n4, n5, n6 = [Node.new(id=i) for i in range(1, 7)]
model.define(n1, n2, n3, n4, n5, n6)
model.define(
    # The first three-clique.
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n3),
    # The second three-clique.
    Edge.new(src=n4, dst=n5),
    Edge.new(src=n4, dst=n6),
    Edge.new(src=n5, dst=n6),
    # The connection between the three-cliques.
    Edge.new(src=n1, dst=n4),
)

# 3. Compute community assignments and inspect
node, label = Node.ref("node"), Integer.ref("label")
infomap = graph.infomap()
model.select(node.id, label).where(infomap(node, label)).inspect()
#    id  label
# 0   1      2
# 1   2      2
# 2   3      2
# 3   4      1
# 4   5      1
# 5   6      1
```

**Weighted Graph Example**

Compute community assignments for each node in an undirected weighted
graph. Here, a six-clique has the edges forming a dumbbell graph
within the six-clique strongly weighted, and the remaining edges
weakly weighted. The graph resolves into two communities, namely the
two three-cliques constituent of the dumbbell embedded in the six-clique.

```python
# 1. Set up a weighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5, n6 = [Node.new(id=i) for i in range(1, 7)]
model.define(n1, n2, n3, n4, n5, n6)
model.define(
    # First embedded three-clique.
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n1, dst=n3, weight=1.0),
    Edge.new(src=n2, dst=n3, weight=1.0),
    # Second embedded three-clique.
    Edge.new(src=n4, dst=n5, weight=1.0),
    Edge.new(src=n4, dst=n6, weight=1.0),
    Edge.new(src=n5, dst=n6, weight=1.0),
    # Slightly weaker connection between the embedded three-cliques.
    Edge.new(src=n1, dst=n4, weight=0.5),
    # Weaker edges connecting the six-clique in full.
    Edge.new(src=n1, dst=n5, weight=0.1),
    Edge.new(src=n1, dst=n6, weight=0.1),
    Edge.new(src=n2, dst=n4, weight=0.1),
    Edge.new(src=n2, dst=n5, weight=0.1),
    Edge.new(src=n2, dst=n6, weight=0.1),
    Edge.new(src=n3, dst=n4, weight=0.1),
    Edge.new(src=n3, dst=n5, weight=0.1),
    Edge.new(src=n3, dst=n6, weight=0.1),
)

# 3. Compute community assignments and inspect
node, label = Node.ref("node"), Integer.ref("label")
infomap = graph.infomap()
model.select(node.id, label).where(infomap(node, label)).inspect()
#    id  label
# 0   1      2
# 1   2      2
# 2   3      2
# 3   4      1
# 4   5      1
# 5   6      1
```

**Notes:**

The relationship(s) returned by `infomap(...)` is (are) cached
for a given set of arguments. All `infomap(...)` calls with the
same arguments will return the same relationship(s).

This implementation of Infomap minimizes the map equation via a
Louvain-like optimization heuristic; this is often referred to as
"core" Infomap in the literature. Computation of the ergodic node
visit frequencies is done via regularized power iteration, with
regularization via a uniform teleportation probability of 0.15,
matching the nominal selection in the literature.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`louvain`()

```python
Graph.louvain(
    max_levels: int = 1,
    max_sweeps: int = 20,
    level_tolerance: float = 0.01,
    sweep_tolerance: float = 0.0001,
    randomization_seed: int = 8675309,
    *,
    diagnostic_info: bool = False
) -> Union[Relationship, Tuple[Relationship, Relationship]]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✘

Not supported by this implementation.

Weighted

✔

Only non-negative weights supported.

Unweighted

✔

Partitions nodes into communities using the Louvain algorithm.

This method detects communities by maximizing a modularity score. It is
only applicable to undirected graphs.

**Parameters:**

- `max_levels` (`int`, default: `1`) - The maximum number of levels at which to optimize. Must be a positive integer. Default is 1.
- `max_sweeps` (`int`, default: `20`) - The maximum number of sweeps within each level. Must be a non-negative integer. Default is 20.
- `level_tolerance` (`float`, default: `0.01`) - Modularity progress threshold to continue to the next level. Must be a non-negative float. Default is 0.01.
- `sweep_tolerance` (`float`, default: `0.0001`) - Modularity progress threshold to continue to the next sweep. Must be a non-negative float. Default is 0.0001.
- `randomization_seed` (`int`, default: `8675309`) - The random number generator seed for the run. Must be a non-negative integer. Default is 8675309.
- `diagnostic_info` (`bool`, default: `False`) - If `True`, returns diagnostic information alongside community assignments. If `False` (default), returns only community assignments.

**Returns:**

- `Relationship or tuple of Relationships` - If `diagnostic_info` is `False` (default), returns a binary
  relationship where each tuple represents a node and its community
  assignment.

  If `diagnostic_info` is `True`, returns a tuple of
  `(community_assignments, diagnostic_info)` where:

  - `community_assignments` is the binary relationship described above
  - `diagnostic_info` is a binary relationship containing one tuple, whose
    second component is a diagnostic string describing the algorithm's
    convergence and termination behavior

**Raises:**

- `DirectedGraphNotSupported` - If the graph is directed.

**Relationship Schema:**

When `diagnostic_info=False` (default):

`louvain(node, community_label)`

- **node** (*Node*): The node.
- **community\_label** (*Integer*): The label of the community the node
  belongs to.

When `diagnostic_info=True`, returns two relationships:

- `louvain(node, community_label)` as described above; and
- `diagnostic_info(diagnostic_name, diagnostic_value)`
- **diagnostic\_name** (*String*): The name of the diagnostic information.
- **diagnostic\_value** (*String*): A diagnostic string describing the
  algorithm's convergence and termination behavior.

**Examples:**

**Unweighted Graph Example**

Compute community assignments for each node in an undirected graph.
Here, an undirected dumbbell graph resolves into two communities,
namely its two constituent three-cliques.

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges for a dumbbell graph
n1, n2, n3, n4, n5, n6 = [Node.new(id=i) for i in range(1, 7)]
model.define(n1, n2, n3, n4, n5, n6)
model.define(
    # The first three-clique.
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n3),
    # The second three-clique.
    Edge.new(src=n4, dst=n5),
    Edge.new(src=n4, dst=n6),
    Edge.new(src=n5, dst=n6),
    # The connection between the three-cliques.
    Edge.new(src=n1, dst=n4),
)

# 3. Compute community assignments and inspect
node, label = Node.ref("node"), Integer.ref("label")
louvain = graph.louvain()
model.select(node.id, label).where(louvain(node, label)).inspect()
#    id  label
# 0   1      2
# 1   2      2
# 2   3      2
# 3   4      1
# 4   5      1
# 5   6      1
```

**Weighted Graph Example**

Compute community assignments for each node in an undirected weighted
graph. Here, a six-clique has the edges forming a dumbbell graph
within the six-clique strongly weighted, and the remaining edges
weakly weighted. The graph resolves into two communities, namely the
two three-cliques constituent of the dumbbell embedded in the
six-clique.

```python
# 1. Set up a weighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5, n6 = [Node.new(id=i) for i in range(1, 7)]
model.define(n1, n2, n3, n4, n5, n6)
model.define(
    # First embedded three-clique.
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n1, dst=n3, weight=1.0),
    Edge.new(src=n2, dst=n3, weight=1.0),
    # Second embedded three-clique.
    Edge.new(src=n4, dst=n5, weight=1.0),
    Edge.new(src=n4, dst=n6, weight=1.0),
    Edge.new(src=n5, dst=n6, weight=1.0),
    # Connection between the embedded three-cliques.
    Edge.new(src=n1, dst=n4, weight=1.0),
    # Weaker edges connecting the six-clique in full.
    Edge.new(src=n1, dst=n5, weight=0.2),
    Edge.new(src=n1, dst=n6, weight=0.2),
    Edge.new(src=n2, dst=n4, weight=0.2),
    Edge.new(src=n2, dst=n5, weight=0.2),
    Edge.new(src=n2, dst=n6, weight=0.2),
    Edge.new(src=n3, dst=n4, weight=0.2),
    Edge.new(src=n3, dst=n5, weight=0.2),
    Edge.new(src=n3, dst=n6, weight=0.2),
)

# 3. Compute community assignments and inspect
node, label = Node.ref("node"), Integer.ref("label")
louvain = graph.louvain()
model.select(node.id, label).where(louvain(node, label)).inspect()
#    id  label
# 0   1      2
# 1   2      2
# 2   3      2
# 3   4      1
# 4   5      1
# 5   6      1
```

**Notes:**

The relationship(s) returned by `louvain(...)` is (are) cached
for a given set of arguments. All `louvain(...)` calls with the
same arguments will return the same relationship(s).

This implementation of the Louvain algorithm is consistent with the
modularity definition (Eq. 1) in "Fast unfolding of communities in
large networks", Blondel et al J. Stat. Mech. (2008) P10008.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

### .`label_propagation`()

```python
Graph.label_propagation(
    max_sweeps: int = 20,
    randomization_seed: int = 8675309,
    *,
    diagnostic_info: bool = False
) -> Union[Relationship, Tuple[Relationship, Relationship]]
```

**Supported Graph Types:**

Graph TypeSupportedNotes

Undirected

✔

Directed

✔

Weighted

✔

Only non-negative weights supported.

Unweighted

✔

Partitions nodes into communities using the Label Propagation algorithm.

This method maps nodes to community assignments via asynchronous
label propagation.

**Parameters:**

- `max_sweeps` (`int`, default: `20`) - The maximum number of sweeps for label propagation to perform. Must be a non-negative integer. Default is 20.
- `randomization_seed` (`int`, default: `8675309`) - The random number generator seed for the run. Must be a non-negative integer. Default is 8675309.
- `diagnostic_info` (`bool`, default: `False`) - If `True`, returns diagnostic information alongside community assignments. If `False` (default), returns only community assignments.

**Returns:**

- `Relationship or tuple of Relationships` - If `diagnostic_info` is `False` (default), returns a binary
  relationship where each tuple represents a node and its community
  assignment.

  If `diagnostic_info` is `True`, returns a tuple of
  `(community_assignments, diagnostic_info)` where:

  - `community_assignments` is the binary relationship described above
  - `diagnostic_info` is a binary relationship containing one tuple, whose
    second component is a diagnostic string describing the algorithm's
    convergence and termination behavior

**Relationship Schema:**

When `diagnostic_info=False` (default):

`label_propagation(node, community_label)`

- **node** (*Node*): The node.
- **community\_label** (*Integer*): The label of the community the node
  belongs to.

When `diagnostic_info=True`, returns two relationships:

- `label_propagation(node, community_label)` as described above; and
- `diagnostic_info(diagnostic_name, diagnostic_value)`
- **diagnostic\_name** (*String*): The name of the diagnostic information.
- **diagnostic\_value** (*String*): A diagnostic string describing the
  algorithm's convergence and termination behavior.

**Examples:**

**Unweighted Graph Example**

Compute community assignments for each node in an undirected graph. Here,
an undirected dumbbell graph resolves into two communities, namely its
two constituent three-cliques.

```python
from relationalai.semantics import Model, Integer
from relationalai.semantics.reasoners.graph import Graph

# 1. Set up an undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=False)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges for a dumbbell graph
n1, n2, n3, n4, n5, n6 = [Node.new(id=i) for i in range(1, 7)]
model.define(n1, n2, n3, n4, n5, n6)
model.define(
    # The first three-clique.
    Edge.new(src=n1, dst=n2),
    Edge.new(src=n1, dst=n3),
    Edge.new(src=n2, dst=n3),
    # The second three-clique.
    Edge.new(src=n4, dst=n5),
    Edge.new(src=n4, dst=n6),
    Edge.new(src=n5, dst=n6),
    # The connection between the three-cliques.
    Edge.new(src=n1, dst=n4),
)

# 3. Compute community assignments and inspect
node, label = Node.ref("node"), Integer.ref("label")
label_propagation = graph.label_propagation()
model.select(node.id, label).where(label_propagation(node, label)).inspect()
#    id  label
# 0   1      2
# 1   2      2
# 2   3      2
# 3   4      1
# 4   5      1
# 5   6      1
```

**Weighted Graph Example**

Compute community assignments for each node in an undirected weighted
graph. Here, a six-clique has the edges forming a dumbbell graph
within the six-clique strongly weighted, and the remaining edges
weakly weighted. The graph resolves into two communities, namely the
two three-cliques constituent of the dumbbell embedded in the
six-clique.

```python
# 1. Set up a weighted, undirected graph
model = Model("test_model")
graph = Graph(model, directed=False, weighted=True)
Node, Edge = graph.Node, graph.Edge

# 2. Define nodes and edges
n1, n2, n3, n4, n5, n6 = [Node.new(id=i) for i in range(1, 7)]
model.define(n1, n2, n3, n4, n5, n6)
model.define(
    # First embedded three-clique.
    Edge.new(src=n1, dst=n2, weight=1.0),
    Edge.new(src=n1, dst=n3, weight=1.0),
    Edge.new(src=n2, dst=n3, weight=1.0),
    # Second embedded three-clique.
    Edge.new(src=n4, dst=n5, weight=1.0),
    Edge.new(src=n4, dst=n6, weight=1.0),
    Edge.new(src=n5, dst=n6, weight=1.0),
    # Slightly weaker connection between the embedded three-cliques.
    Edge.new(src=n1, dst=n4, weight=0.5),
    # Weaker edges connecting the six-clique in full.
    Edge.new(src=n1, dst=n5, weight=0.1),
    Edge.new(src=n1, dst=n6, weight=0.1),
    Edge.new(src=n2, dst=n4, weight=0.1),
    Edge.new(src=n2, dst=n5, weight=0.1),
    Edge.new(src=n2, dst=n6, weight=0.1),
    Edge.new(src=n3, dst=n4, weight=0.1),
    Edge.new(src=n3, dst=n5, weight=0.1),
    Edge.new(src=n3, dst=n6, weight=0.1),
)

# 3. Compute community assignments and inspect
node, label = Node.ref("node"), Integer.ref("label")
label_propagation = graph.label_propagation()
model.select(node.id, label).where(label_propagation(node, label)).inspect()
#    id  label
# 0   1      2
# 1   2      2
# 2   3      2
# 3   4      1
# 4   5      1
# 5   6      1
```

**Notes:**

The relationship(s) returned by `label_propagation(...)` is (are) cached
for a given set of arguments. All `label_propagation(...)` calls with the
same arguments will return the same relationship(s).

This implementation of asynchronous label propagation breaks ties
between neighboring labels with equal cumulative edge weight (and
frequency in the unweighted case) uniformly at random, but with a
static seed.

Edges with zero weight still influence the result, for example if
a node has only zero-weight edges.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Graph reasoning](/build/reasoning/graph/index.md)1) [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1. [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)

## Used By

1. [semantics](/api/python/v2.2/semantics/index.md) / [reasoners](/api/python/v2.2/semantics/reasoners/index.md) / [predictive](/api/python/v2.2/semantics/reasoners/predictive/index.md) / [estimators](/api/python/v2.2/semantics/reasoners/predictive/estimators/index.md) / [relational](/api/python/v2.2/semantics/reasoners/predictive/estimators/relational/index.md)1) [gnn](/api/python/v2.2/semantics/reasoners/predictive/estimators/relational/gnn/index.md)1. [GNN](/api/python/v2.2/semantics/reasoners/predictive/estimators/relational/gnn/gnn_class/index.md)
   2) [relfm](/api/python/v2.2/semantics/reasoners/predictive/estimators/relational/relfm/index.md)1) [RelFM](/api/python/v2.2/semantics/reasoners/predictive/estimators/relational/relfm/relfm_class/index.md)

## Referenced By

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md)1) [Graph reasoning](/build/reasoning/graph/index.md)1. [Create a graph](/build/reasoning/graph/create-a-graph/index.md)1) [Understand graph basics](/build/reasoning/graph/create-a-graph/index.md#understand-graph-basics)
               2) [Choose a graph type](/build/reasoning/graph/create-a-graph/index.md#choose-a-graph-type)
            2. [Run a Graph Algorithm](/build/reasoning/graph/run-an-algorithm/index.md)1) [Use a graph algorithm](/build/reasoning/graph/run-an-algorithm/index.md#use-a-graph-algorithm)
               2) [Available Algorithms](/build/reasoning/graph/run-an-algorithm/index.md#available-algorithms)
         2) [Path reasoning](/build/reasoning/path/index.md)1) [Use path results](/build/reasoning/path/use-path-results/index.md)1. [Keep path queries fast](/build/reasoning/path/use-path-results/index.md#keep-path-queries-fast)
         3) [Predictive reasoning](/build/reasoning/predictive/index.md)1) [Overview](/build/reasoning/predictive/index.md)1. [What predictive reasoning is](/build/reasoning/predictive/index.md#what-predictive-reasoning-is)
            2) [Construct a graph](/build/reasoning/predictive/construct-a-graph/index.md)
            3) [Predict with RelFM](/build/reasoning/predictive/use-relfm/index.md)
   2) [Deploy](/deploy/index.md)1) [Configure deployment](/deploy/configure-deployment/index.md)
   3) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.1.0](/release-notes/python/2.1.0/index.md)1) [Bug Fixes](/release-notes/python/2.1.0/index.md#bug-fixes)
